I have a data producer that produces data that is used by a number of a different consumers (let's call them Cs). Each C has its own set of data that it's interested in. The data producer has weak references to the Cs so they can be notified for updates.
Each C is also used by a number of independent components, so no single one component can tell when the C is no longer needed, so we have to leave it to the JVM to determine when C is GC-able.
The goal here is to be notified when a C becomes obsolete, so the data producer can turn off data that is only interesting to that unused C.
As I mentioned earlier, the data producer always has weak references to the Cs, so it's easy to do it when a C is GCed. However, I noticed that the Cs usually stick around in the VM for an extended period of time before it's finally GC-ed and all this while, the data producer is producing a LOT of data it should have needed to.
Is there any way for me to force the GC of unused Cs? I am hoping for yes, but I'm expecting a No, so as a follow-up question, does anyone have a good suggestion to how I can (re)design this to make it work better/more efficiently?
Thank you!!
Some answers below make a lot of good points - in particular the suggestion to force users of C to subscribe and unsubscribe. This is difficult because:
C is just one possible implementation of an interface I (which doesn't have this subscription requirement), which is what the users really use. The C implementation is injected during run-time, so we can't force the users to comply to C-specific requirements. (Ouch?)