Garbage collection · Topic 3 of 6
Reachability and references
Definition​
The collector frees only objects that nothing can reach any more. A normal (strong) reference keeps an object alive. A WeakReference does not: once nothing else refers to the object, the collector may free it, which is useful for caches.
Example code​
A weakly referenced object disappears after a collection
import java.lang.ref.WeakReference;
class Demo {
public static void main(String[] args) throws InterruptedException {
Object strong = new Object();
WeakReference<Object> weakOfStrong = new WeakReference<>(strong);
WeakReference<Object> weak = new WeakReference<>(new Object()); // nothing else refers to it
System.gc(); // a request to collect now
Thread.sleep(100);
System.out.println("still reachable object: " + (weakOfStrong.get() != null));
System.out.println("unreachable object: " + (weak.get() != null));
System.out.println(strong != null); // keeps 'strong' alive until here
}
}
// Output:
// still reachable object: true
// unreachable object: false
// true
Finished this page? Track your progress (saved only in your browser).