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