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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

 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.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}