/home/wpollock1/public_html/AJava/RefDemo.java
// Demo of using weak references. (Didn't use SoftReferences since the
// garbage collector ("GC") may not reclaim such objects when memory is
// not low.
//
// Written 5/2020 by Wayne Pollock, Tampa Florida USA
import java.lang.ref.*;
public class RefDemo {
public static void main ( String[] args ) {
Foo f = new Foo(); // f contains a strong reference to the new object
WeakReference<Foo> wr = new WeakReference<>( f );
f = null; // No strong references exist to the object after this
Foo foo = wr.get(); // Will return null if object was GC'ed
System.out.println( foo );
foo = null; // No strong references exist to the object after this
System.gc();
foo = wr.get();
System.out.println( foo );
}
private static class Foo {
public String toString () {
return "I'm a Foo object";
}
}
}