Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Practical Uses for WeakReferences

DZone's Guide to

Practical Uses for WeakReferences

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

 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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}