Sobes.tech
Senior

What types of references in Java do you know?

sobes.tech AI

Answer from AI

In Java, there are the following types of references that manage object lifetimes and garbage collection:

  1. Strong Reference — a normal reference that prevents the object from being garbage collected. As long as strong references exist, the object will not be removed.

  2. Soft Reference — used for caching. Objects with soft references will only be garbage collected when the JVM needs memory.

  3. Weak Reference — objects with such references can be collected during the next garbage collection cycle, even if weak references still exist.

  4. Phantom Reference — used to track when an object is ready to be collected but has not yet been removed. It allows performing additional actions after the object’s finalization.

Example of creating a weak reference:

Object obj = new Object();
WeakReference<Object> weakRef = new WeakReference<>(obj);
obj = null; // now the object is only accessible through the weak reference

These types of references help manage memory and optimize object handling, especially in caches and resource-constrained systems.

What types of references in Java do you know? — Java - sobes.tech