當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java java.lang.ref.PhantomReference用法及代碼示例


當我們在Java中創建一個對象時,默認情況下對象是強的。要創建虛擬引用對象,我們必須向 JVM 顯式指定它。幻像引用對象是由於幻像引用對象有資格進行垃圾回收而創建的,但它不會立即被收集。相反,它被推入ReferenceQueue,以便可以清除所有此類排隊的引用。

該類的構造函數如下表所示

構造函數參數 構造函數說明
PhantomReference (T,ReferenceQueue <T> q): 創建一個新的幻像引用,該引用引用給定的對象並注冊到給定的隊列中。可以使用空隊列創建幻像引用,但這樣的引用是完全無用的:它的 get 方法將始終返回 null,並且由於它沒有隊列,因此永遠不會入隊。

從Reference類繼承的方法如下:

方法名稱 方法說明
get() 返回此引用對象的指示對象。由於幻像引用的指示對象始終不可訪問,因此此方法始終返回 null。
clear() 清除該引用對象。調用此方法不會導致此對象入隊。
enque() 將此引用對象添加到其注冊的隊列(如果有)。
isEnqueued() 告知此引用對象是否已被程序或垃圾Collector排隊。

示例 1:

Java


// Java Program to illustrate PhantomReference class
// of java.lang.ref package 
// Importing PhantomReference and ReferenceQueue classes
// from java.lanf.ref package
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
// Class 1
// Helper class
class HelperClass {
    // Method inside HelperClass
    void Display()
    {
        // Print statement whenever the function is called
        System.out.println("Display Function invoked ...");
    }
}
// Class 2
// Main class
public class GFG {
    // MyClass
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a strong object of HelperClass
        HelperClass obj = new HelperClass();
        // Creating a reference queue of HelperClass type
        ReferenceQueue<HelperClass> rq
            = new ReferenceQueue<>();
        // Creating a phantom reference object using rq
        PhantomReference<HelperClass> pobj
            = new PhantomReference<>(obj, rq);
        // Display message only
        System.out.println(
            "-> Calling Display Function using strong object:");
        //  Calling the display method over the object of
        //  HelperClass
        obj.Display();
        // Display message for better readability
        System.out.println("-> Object set to null");
        obj = null;
        // Getting elements in PhantomReference object
        // using standard get() method
        obj = pobj.get();
        // Display status of  objects after fetching
        // PhantomReference class objects
        System.out.println(
            "-> Object status after fetching from PhantomReference now : "
            + obj);
        // Display message only
        System.out.println(
            "-> Calling Display Function after retrieving from weak Object");
        // Try block to check for exceptions
        try {
            obj.Display();
        }
        // Catch block to handle the exceptions
        catch (Exception E) {
            // Print message when an exception occurred
            System.out.println("-> Error : " + E);
        }
    }
}
輸出
-> Calling Display Function using strong object:
Display Function invoked ...
-> Object set to null
-> Object status after fetching from PhantomReference now : null
-> Calling Display Function after retrieving from weak Object
-> Error : java.lang.NullPointerException

Hence, it is seen that unlike Soft and Weak References, Phantom Reference always returns null.

示例 2:

Java


// Java Program to illustrate PhantomReference class
// of java.lang.ref package 
// Importing Phantomreference and RefereenceQueue classes
// from java.lang.ref package
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
// Class 1
// HelperClass
class X {
    // Method
    // To print simply
    void show()
    {
        // Display message whenever
        // show() method is called
        System.out.println("show () from X invoked..");
    }
}
// Class 2
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating default object of X class
        X obj = new X();
        // Creating new reference queue object
        ReferenceQueue<X> rq = new ReferenceQueue<X>();
        // Creating an object of PhantomReference class
        // of X class type with RefereneQueue object
        // reference queue
        PhantomReference<X> phantomobj
            = new PhantomReference<X>(obj, rq);
        // Display message
        System.out.println(
            "-> Trying to retrieve object from Phantom Reference :");
        // Try block to check for exceptions
        try {
            // this will always throw error as it has been
            // collected
            //  by the garbage collector
            phantomobj.get().show();
        }
        // Catch block to handle the exceptions
        catch (Exception e) {
            // Print and display the exception
            System.out.println(e);
        }
    }
}
輸出
-> Trying to retrieve object from Phantom Reference :
java.lang.NullPointerException


相關用法


注:本文由純淨天空篩選整理自varunkedia大神的英文原創作品 java.lang.ref.PhantomReference Class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。