当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。