Tuesday, August 2, 2016

Reference Type Strong/Soft/Weak/Phantom

Strong
Regular reference

Soft
Used for memory cache, only gc when memory not enough

Weak
Used for storing data, only gc on the second time. Example: ClassLoader

Phantom
Used only for monitoring if object has already been gc

Reference Queue
When an object has been gc, we can poll it from ReferenceQueue


import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class ReferenceType {
 public static void main(String[] args) throws InterruptedException{
  String s1 = new String("aaa");
  String s2 = new String("bbb");
  String s3 = new String("ccc");
  
  ReferenceQueue<String> srq = new ReferenceQueue<String>();
  SoftReference<String> ss = new SoftReference<String>(s1,srq);
  ReferenceQueue<String> wrq = new ReferenceQueue<String>();
  WeakReference<String> ws = new WeakReference<String>(s2,wrq);
  ReferenceQueue<String> prq = new ReferenceQueue<String>();
  PhantomReference<String> ps = new PhantomReference<String>(s3,prq);
  
  s1 = null;
  s2 = null;
  s3 = null;
  
  System.gc();
    
  System.out.println("ss="+ss.get());
  System.out.println("srq="+srq.poll());
  System.out.println("ws="+ws.get());
  System.out.println("wrq="+wrq.poll());
  System.out.println("ps="+ps.get());
  System.out.println("prq="+prq.poll());
 }
}


Output result
ss=aaa
srq=null
ws=null
wrq=java.lang.ref.WeakReference@15db9742
ps=null
prq=java.lang.ref.PhantomReference@6d06d69c




No comments:

Post a Comment