Practical Uses for WeakReferences
Join the DZone community and get the full member experience.
Join For Free 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.
Object (computer science)
garbage collection
Cache (computing)
Data (computing)
Garbage (computer science)
Data Types
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments