Aleyna
Aleyna

Reputation: 1857

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. 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?

edit: I added the implementation of Channel above as well. Also in main(...) method, I have the following:

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

Upvotes: 1

Views: 79

Answers (1)

ciamej
ciamej

Reputation: 7068

It's impossible that MyListener gets garbage collected, if you still have strong reference to MyModule.

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).

How do you even know that listener is garbage collected? You probably check whether it's present in the backend WeakHashMap. It's not there so you claim it's 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. If you have, then check if SubModule has a valid reference to MyListener.

Upvotes: 1

Related Questions