Understanding References in Java

0 216

Get real time updates directly on you device, subscribe now.

In this journal entry we will taking a deep dive into understanding what are References in Java and how are they effected during the Garbage Collection process.

References in Java

Java has four main types of references.

  • Weak References
  • Strong References
  • Soft References
  • Phantom References

Most of the developers ask the question that why there are differenct types of references? What are they used for? To understand these lets understand these references in a more detailed way.

Read More: Reference Queues

Strong Reference: Strong references in Java are used everywhere. The object is created and then assigned to a reference. If the object has a strong reference, then the object will never be garbage collected.

DevelopersJournal objDevelopersJournal = new DevelopersJournal();

Soft Reference: If an object has no strong reference but has a soft reference, then the garbage collector reclaims this object’s memory. This needs to be done when GC needs to free up some memory. To get Object from a soft reference, one can invoke the get() method. If the object is not GCed, it returns the object, otherwise , it returns null.

Weak Reference: If an object has no strong reference but has a weak reference then GC reclaims this object’s memory in next run even though there is enough memory.

Phantom Reference: If an object does not have any of the above references then it may have a phantom reference. Phantom references can’t be accessed directly. When using a get() method it will always return null.

Phantom Reference can be used in situations, where sometimes using finalize() is not sensible.This is a special reference which says that the object was already finalized, and the garbage collector is ready to reclaim its memory.