Search⌘ K
AI Features

Reference Strengths

Explore the different types of references in Java such as strong, weak, and phantom references, and understand their roles in memory management and garbage collection. Learn how reference queues work and how phantom references aid in resource cleanup beyond object finalization.

We'll cover the following...
1.

What are the different reference types in Java?

Show Answer
1 / 3
Java
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.");
}
}
}

Note that in the above code if instead of creating a String object using new, we initialized the str variable using a string literal like str = "Educative.io"; then the program behavior would be different. The String literal isn't allocated on the heap rather it lives in a special area called the String pool. The String pool consists of string literals that can be reused and aren't removed from the pool even when there may be no reference to them. Therefore, if you ...