Skip to content

Instantly share code, notes, and snippets.

@yssharma
Created November 3, 2012 13:19
Show Gist options
  • Save yssharma/4007364 to your computer and use it in GitHub Desktop.
Save yssharma/4007364 to your computer and use it in GitHub Desktop.
Java Weak - Soft - Phantom References (Confused Coders)
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
class SomeClass{
/** toString() is called every time we print the object. **/
public String toString(){
return "I am an Object, Still in Heap";
}
/** finalize() would be called just before the object dies **/
public void finalize(){
System.out.println("The GC just shot me..I am dying ..");
}
}
public class References {
public static void main(String[] args) throws InterruptedException{
ReferenceQueue refQueue = null;
System.out.println("\n--- Strong Ref -------------------");
SomeClass strongRef = new SomeClass();
System.gc();Thread.sleep(2000);
System.out.println("Post GC: "+strongRef);
System.out.println("\n--- Weak Ref ---------------------");
refQueue = new ReferenceQueue();
WeakReference weakRef
= new WeakReference(new SomeClass(),refQueue);
System.out.println("Pre GC, weakRef.get(): "+weakRef.get());
System.out.println("Pre GC, refQueue.poll(): "+refQueue.poll());
System.gc(); Thread.sleep(2000);
System.out.println("Post GC, weakRef.get(): "+weakRef.get());
System.out.println("Post GC, refQueue.poll(): "+refQueue.poll());
System.out.println("\n--- Soft Ref ---------------------");
refQueue = new ReferenceQueue();
SoftReference softRef
= new SoftReference(new SomeClass(), refQueue);
System.out.println("Pre GC, softRef.get():"+softRef.get());
System.out.println("Pre GC, refQueue.poll():"+refQueue.poll());
System.gc();Thread.sleep(2000);
System.out.println("Post GC, softRef.get():"+softRef.get());
System.out.println("Post GC, refQueue.poll():"+refQueue.poll());
System.out.println("\n--- Phantom Ref ------------------");
refQueue = new ReferenceQueue();
PhantomReference phantomRef
= new PhantomReference(new SomeClass(), refQueue);
System.out.println("Pre GC, phantomRef.get():"+phantomRef.get());
System.out.println("Pre GC, refQueue.poll():"+refQueue.poll());
System.gc();Thread.sleep(2000);
System.out.println("Post GC, phantomRef.get():"+phantomRef.get());
System.out.println("Post GC, refQueue.poll():"+refQueue.poll());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment