I have an object Producer which internally starts a thread that will listen for some network events, and at most times block on a receive() method. In this Producer object I have a WeakHashMap<Integer, Vector<IConsumer>> containing at hash map with keys being the events that the Producer can produce, and the value being a list of consumer that has registered on these events.
Now I have a Main object which constructs some Manager. The Manager the constructs one single Producer and any number of ConcreteConsumers implements IConsumer. The Manager contains a reference to the Producer and the ConcreteConsumers.
Is this a valid construction, will the Vector<IConsumer> not be eligible for GC immediately after insertion in the WeakHashMap<Integer, Vector<IConsumer>> as there are not reference to the actual vector? There are only references to the Producer and the ConcreteConsumers directly. If so, how can I solve this?
Next what happens is that the Main object drops the reference to the Manager, which should cause all the ConcreteConsumers to be eligible for GC, which is what I want.
But, I also want the actual Producer object to be eligible for GC and for the internal thread to stop executing at this point. Any suggestions on how to do this?
It’s the key in
WeakHashMapthat has the weak reference. The value is strongly referenced. The entry will be removed some time after there are no strong references to the key, anIntegerin this case. That is the very same instance ofInteger, not just an instance with the same value. Values types aren’t particularly useful as keys toWeakHashMap.(
WeakHashMapis not useful as a cache (you want to be usingSoftReferences, and probably someone else’s library).)