Immanuel Kant
Immanuel Kant

Reputation: 527

Java: WeakReference.get() returns differently after System.gc()

I tried to see when weak reference returns null by get():

String string = new String("abc");
WeakReference<String> wi = new WeakReference<>(string);
WeakReference<String> sr = new WeakReference<>(new String("another"));
System.out.println(wi.get());
System.out.println(sr.get());
System.gc();
System.out.println("After gc() wi = " + wi.get());
System.out.println("After gc() sr =: " + sr.get());

It prints:

abc
another
After gc() wi = abc
After gc() sr =: null

Why after gc(), wi still holds reference, and sr is holding null? I changed String type into Integer or my own class, same result.

What makes the core difference here?

Upvotes: 2

Views: 56

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

A weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference.

Because abc is held by the strong reference string, the object will not be eligible to GC it as there is an existing living reference to it and thus the weak reference still refers to it. In the second case, the only reference to another is sr a weak reference and GC is then free to make what it refers to as eligible to deletion.

Deletion may be "virtual", that depends on the Garbage Collector used.

Upvotes: 4

Related Questions