Reference types

Reference in term of variable references an object (important for GC). Object not GC'd until references are released.

Actual available types of references:

  • Strong ->

  • Soft -> object will be collected if there is a memory pressure

  • Weak -> object will be collected immediately

Person p = new Person(); // person is a strong reference
WeakReference<Person> wr = new WeakReference<Person>(p);  // this is wek ref to person object

Person p1 = wr.get();    // p1 is a strong reference to the same object as person var points to
System.out.println(p1);  // assuming that this gives hash code Person@1234c

p = null;
p1 = null;
Person p2 = wr.get(); // even though p and p1 are pointing to null, as far as there was no GC and 
                      // there is not memory pressure, p2 will point to the same Person@1234c
                      
p2 = null;
System.gc();
Person p3 = wr.get();
System.out.println(p3);  // in this case because of GC, p3 will be null
                      
                      
  • Phantom

Last updated