Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy is my instance garbage collected
    text
    copied!<p>I have the following class hierarchy. For some reason, my listener gets garbage collected even though I maintain a strong reference to it.</p> <pre><code>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&lt;MyListener, Boolean&gt; backend = new WeakHashMap&lt;MyListener, Boolean&gt;(); Set&lt;MyListener&gt; 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); } } } </code></pre> <p>The class Channel maintains a set of listeners in a WeakHashSet. So I register the listener in MySubModule along with keeping a strong reference to it in the same class(variable listener). However, JVM still garbage collects the listener instance. Shouldn't it stay in the WeakHashSet as soon as there is strong reference to it? In which case, I truly believe I have one above. Can someone tell me what wrong I am doing here?</p> <p>edit: I added the implementation of Channel above as well. Also in main(...) method, I have the following:</p> <pre><code>static void main(...) { Channel ch = new Channel(); MyModule myModule = new MyModule(ch); // do some real stuff here. } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload