0
B b = new B();

Here b is strong reference, then we set b as null.

b = null;

then GC will reclaim the object which referenced to b when GC happens.

My question is what is the point of using weak reference? as i understand it, the only reason to use weak reference, so we can still get the object even after we set reference as null before GC reclaims it. am i correct?

ning morris
  • 257
  • 1
  • 2
  • 8
  • [The Javadoc](https://docs.oracle.com/javase/9/docs/api/java/lang/ref/WeakReference.html) describes some uses. – Andy Turner Oct 12 '18 at 21:40
  • 1
    `so we can still get the object even after we set reference as null before GC` No, it's so the reference won't prevent the GC from collecting. A regular reference (strong) hold the object no matter what. A weak reference allows other code to finish with the reference and allows the object to be GC'ed when that other code releases the reference. – markspace Oct 12 '18 at 21:47
  • A WeakReference will keep a reference provided it is still being used somewhere else in the code. It is useful when you don't expect to be notified the reference is no longer needed. – Peter Lawrey Oct 13 '18 at 09:56

0 Answers0