Is there a practical use for weak references?

user496949 picture user496949 · Jan 9, 2012 · Viewed 25.8k times · Source

Possible Duplicate:
Weak references - how useful are they?

Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?

Answer

Peter Lawrey picture Peter Lawrey · Jan 9, 2012

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.