Reference Strengths

This lesson explains the different reference types in Java.

We'll cover the following...

Question # 1

What are the different reference types in Java?

  • Strong Reference

  • Weak Reference

  • Soft Reference

  • Phantom Reference

Question # 2

What is a strong reference?

These are the references we are all used to. The object on the heap is not garbage collected while there is a strong reference pointing to it, or if it is strongly reachable through a chain of strong references.

Question # 3

What are Weak References?

A weakly referenced object is cleared by the Garbage Collector when it’s weakly reachable. Weak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference. A weak reference to an object from the heap is most likely to not survive after the next garbage collection process. WeakHashMap is an example datastructure using weak references.

The referent is wrapped by an instance of the WeakReference class like below:

        String str = new String("Educative.io"); // This is the referent
        WeakReference<String> myString = new WeakReference<>(str); // referent being passed into the constructor

        // Try invoking the GC, but no guarantees it'll run
        Runtime.getRuntime().gc();

        if (myString.get() != null) {
            System.out.println(myString.get());
        } else {
            System.out.println("String object has been cleared by the Garbage Collector.");
        }

The idiomatic usage of a weak reference always requires checking whether the underlying variable has been removed by the GC.

Press + to interact
import java.lang.ref.WeakReference;
class Demonstration {
public static void main( String args[] ) {
String str = new String("Educative.io"); // This is a string reference
WeakReference<String> myString = new WeakReference<>(str);
str = null; // nulling the strong reference
// Try invoking the GC, but no guarantees it'll run
Runtime.getRuntime().gc();
if (myString.get() != null) {
System.out.println(myString.get());
} else {
System.out.println("String object has been cleared by the Garbage Collector.");
}
}
}
...