RefDemo.java

Download RefDemo.java

 1: // Demo of using weak references.  (Didn't use SoftReferences since the
 2: // garbage collector ("GC") may not reclaim such objects when memory is
 3: // not low.
 4: //
 5: // Written 5/2020 by Wayne Pollock, Tampa Florida USA
 6: 
 7: import java.lang.ref.*;
 8: 
 9: public class RefDemo {
10:    public static void main ( String[] args ) {
11:       Foo f = new Foo();  // f contains a strong reference to the new object
12:       WeakReference<Foo> wr = new WeakReference<>( f );
13:       f = null;  // No strong references exist to the object after this
14: 
15:       Foo foo = wr.get();  // Will return null if object was GC'ed
16:       System.out.println( foo );
17: 
18:       foo = null;  // No strong references exist to the object after this
19:       System.gc();
20:       foo = wr.get();
21:       System.out.println( foo );
22:    }
23: 
24:    private static class Foo {
25:       public String toString () {
26:          return "I'm a Foo object";
27:       }
28:    }
29: }