An Overview of Types of Reference Variables in Java

Sachin Bhandari
2 min readDec 4, 2022

--

Memory diagram of an object

Strong Reference

A hard (or strong) reference is the default type of reference.

The object can’t be garbage collected if it’s reachable through any strong reference.

List<String> list = new ArrayList<>();
list=null

Now the object of ArrayList() is not referenced by any reference variable so now it will be collected by garbage collector.

Weak Reference

weak reference acts as a holder to an object.

Using a week reference we can simply rely on garbage collectors ability to reachability of an object on the heap.

A great example is weak hash map which works like normal HashMap, but its keys are weakly referenced, and they are automatically removed when the referent is cleared i.e. when the hashmap is not used by any object any longer.

Soft Reference

A soft reference is very similar to weak reference ,except that it is garbage collected only when there is some memory issue like running out of memory.

The garbage collector will reclaim the memory of all soft reference’s objects before throwing out of memory error.

All soft references to objects reachable only by soft reference should be cleared out before the out of memory error exception is thrown.

SoftReference<List<String>> listReference = new SoftReference<List<String>>(new ArrayList<String>());

A good example of using soft reference is to implement our own caching.

The cache will stay on memory until there is some memory issue,and will be reclaimed by garbage collector before throwing out of memory error.

Phantom Reference

Similarly to weak references, phantom references don’t prohibit the garbage collector from enqueueing objects for being cleared. The difference is phantom references must be manually polled from the reference queue before they can be finalized. That means we can decide what we want to do before they are cleared.

Phantom references are great if we need to implement some finalization logic, and they’re considerably more reliable and flexible than the finalize method.

Connect with me on Linkedin

[1]: Image- https://www.geeksforgeeks.org/reference-variable-in-java/

[2]: https://www.baeldung.com/java-reference-types

--

--