WeakRefTest.java



/** Reference でオブジェクトの参照を監視する */
import java.lang.ref.*;
import java.awt.*;
public class WeakRefTest {

  /** 最初に呼び出されるメソッド */
    public static void main( String argv[] ) {
        WeakReference ref;
        Color ivory = new Color( 255, 255, 250 ); // オブジェクトの生成
        ref = new WeakReference( ivory );         // 監視用の参照
   //step1:
        System.out.println( "Step1:Object is referred." );
        System.out.println( "\tivory refers " + ivory.toString() );
   //step2:
        System.out.println( "Step2:Object is not referred." );
        ivory = null;  // オブジェクトへの参照を消す
        if( ref.get() != null )
            System.out.println( "\tref refers " + ref.get().toString() );
        else
            System.out.println( "\tref refers null" );
   //step3:
        System.out.println( "Step3:GC is called." );
        System.gc();  // ガーベジコレクションを強制的に実行
        if( ref.get() != null )
            System.out.println( "\tref refers " + ref.get().toString() );
        else
            System.out.println( "\tref refers null" );
    }
}