Reference Strengths

This lesson explains the different reference types in Java.

We'll cover the following...
1.

What are the different reference types in Java?

0/500
Show Answer
1 / 3
Press + to interact
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 run the same program initializing the str variable with a string literal, the print message would be different.

1.

What are soft references?

0/500
Show Answer
1 / 3
Press + to interact
Java
import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
class Demonstration {
public static void main( String args[] ) {
// Declare an integer
Integer i = new Integer(420);
// Create a reference queue typed on Integer
ReferenceQueue<Integer> q = new ReferenceQueue<>();
// Create the weak reference and pass the queue as a param
WeakReference<Integer> wrappedInt = new WeakReference<>(i, q);
// Prints the wrapped integer.
System.out.println(wrappedInt.get().toString());
// Check if the queue has any item in it. It should return
// null since no GC has been performed
System.out.println(q.poll() == null ? "queue is empty" : "queue has an element");
}
}

Now we'll nullify the variable i = null and run the GC and this time the variable should be enqueued in the reference queue we passed in.

  
...