Practical Uses for WeakReferences
This is based on answers to Is there a practical use for weak references?
Question
Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?Answers
If you want to keep a reference to something as long as it is used elsewhere e.g. a Listener, you can use a weak reference.WeakHashMap can be used as a short lived cache of keys to derived data. It can also be used to keep information about objects used else where and you don't know when those objects are discarded.
BTW Soft References are like Weak references, but they will not always be cleaned up immediately. The GC will always discard weak references when it can and retain Soft References when it can.
There is another kind of reference called a Phantom Reference. This is used in the GC clean up process and refers to an object which isn't accessible to "normal" code because its in the process of being cleaned up.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Tags:






Comments
Konrad Garus replied on Thu, 2012/11/22 - 4:04pm
Can you elaborate on the example with a reference to something that is good as long as it's used elsewhere? I understand the idea, but can't think of a concrete realistic use case.
Daniel Michalik replied on Thu, 2012/11/22 - 11:10pm
Storing listener with weak reference in event source class is not as good idea as it seems at first glance. Listener instance is often created using anonymous class without reference to it, therefore the only pointer to listener is only from weakreference object which does not prevent garbage collector to remove it from memory.
<code>
aButton.addActionListener(new ActionListener() { ... });
</code>
Pierre-Yves Saumont replied on Thu, 2012/12/06 - 9:59am
in response to:
Konrad Garus
Think of a lazy initialized value. It is uninitialized until some user access it for the first time. So, if the initialization takes some time, the first access is slow, and subsequent accesses are faster. If you have many data like this, you may initialize them on the first access and keep a weak reference to them. The corresponding objects will stay in memory as long as the user holds needs (since he will have a hard reference to it). Once he does not need it anymore, you stay with a weak reference. If another user wand the data, he gets it fast as long as the weak reference holds, i.e. has long as there is enough memory. If memory gets low, the object is garbage collected and we are taken back the original case. If a user now wants the object, he will have to wait for a new initialization.