简体   繁体   English

为什么我的实例垃圾被收集

[英]why is my instance garbage collected

I have the following class hierarchy. 我有下面的类层次结构。 For some reason, my listener gets garbage collected even though I maintain a strong reference to it. 出于某种原因,即使我对其进行了严格的引用,我的侦听器也会收集垃圾。

class MyModule { 
   MySubModule submodule = null;

   MyModule(Channel ch) {
      submodule = new MySubModule(ch);
   }
}

class MySubModule { 
   MyListener listener = null;

   MySubModule(Channel ch) {
      listener = new MyListener();
      ch.subscribe(listener);
   }
}

class Channel { 
   Map<MyListener, Boolean> backend = new WeakHashMap<MyListener, Boolean>();
   Set<MyListener> listeners = Collections.newSetFromMap(backend);

   void subscribe(MyListener listener) {
       listeners.add(listener);
   }

   void fireListeners() {
       // listeners get garbage collected so they won't get fired
       for (MyListener listener:listeners) {
          listener.observe(someEvt);
       }
   }
}

The class Channel maintains a set of listeners in a WeakHashSet. Channel类在WeakHashSet中维护一组侦听器。 So I register the listener in MySubModule along with keeping a strong reference to it in the same class(variable listener). 因此,我在MySubModule中注册了侦听器,并在同一类(变量侦听器)中对其进行了强有力的引用。 However, JVM still garbage collects the listener instance. 但是,JVM仍会垃圾收集侦听器实例。 Shouldn't it stay in the WeakHashSet as soon as there is strong reference to it? 一旦强烈引用它,它不应该留在WeakHashSet中吗? In which case, I truly believe I have one above. 在那种情况下,我真的相信我上面有一个。 Can someone tell me what wrong I am doing here? 有人可以告诉我我在这里做什么错吗?

edit: I added the implementation of Channel above as well. 编辑:我也添加了Channel的实现。 Also in main(...) method, I have the following: 同样在main(...)方法中,我有以下内容:

static void main(...) {
    Channel ch = new Channel();
    MyModule myModule = new MyModule(ch);
    // do some real stuff here.
}

It's impossible that MyListener gets garbage collected, if you still have strong reference to MyModule. 如果您仍然强烈引用MyModule,则MyListener不可能被垃圾回收。

Either you do not set correctly submodule, or you do not set correctly listener, or you never add your listener to the backend WeakHashMap (which I guess is the most probable). 您可能未正确设置子模块,或者未正确设置侦听器,或者从未将侦听器添加到后端WeakHashMap(我猜这是最可能的)。

How do you even know that listener is garbage collected? 您甚至如何知道监听器已被垃圾回收? You probably check whether it's present in the backend WeakHashMap. 您可能会检查后端WeakHashMap中是否存在它。 It's not there so you claim it's gc'ed. 它不在那里,所以您声称它已经被gc'ed了。 But in reality it was never added to it. 但实际上,它从未被添加。 Let me know if that's correct. 让我知道是否正确。

First check if you really have strong reference to Module and SubModule. 首先检查您是否真的对Module和SubModule有很强的引用。 If you have, then check if SubModule has a valid reference to MyListener. 如果有,请检查SubModule是否具有对MyListener的有效引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM