📜  Java的.lang.ref.PhantomReference类在Java中

📅  最后修改于: 2022-05-13 01:55:18.892000             🧑  作者: Mango

Java的.lang.ref.PhantomReference类在Java中

当我们在Java创建对象时,对象默认是强对象。要创建 Phantom 引用对象,我们必须向 JVM 显式指定它。幻像引用对象是因为幻像引用对象有资格进行垃圾收集而创建的,但不会立即收集。相反,它被推入一个 ReferenceQueue,以便可以清除所有此类排队的引用。

该类的构造函数如下表所示

Constructor ParametersConstructor Description
PhantomReference (T,ReferenceQueue q) :Creates a new phantom reference that refers to the given object and is registered with the given queue. It is possible to create a phantom reference with a null queue, but such a reference is completely useless: Its get method will always return null and, since it does not have a queue, it will never be enqueued.

从Reference Class继承的方法如下:

Method NameMethod Description
get()Returns this reference object’s referent. Because the referent of a phantom reference is always inaccessible, this method always returns null.
clear()Clears this reference object. Invoking this method will not cause this object to be enqueued. 
enque()Adds this reference object to the queue with which it is registered, if any.
isEnqueued()Tells whether this reference object has been enqueued, either by the program or by the garbage collector.

示例 1:



Java
// Java Program to illustrate PhantomReference class
// of java.lang.ref package 
  
// Importing PhantomReference and ReferenceQueue classes
// from java.lanf.ref paackage
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 rq
            = new ReferenceQueue<>();
  
        // Creating a phantom reference object using rq
        PhantomReference 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);
        }
    }
}


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 rq = new ReferenceQueue();
  
        // Creating an object of PhantomReference class
        // of X class type with RefereneQueue object
        // reference queue
        PhantomReference phantomobj
            = new PhantomReference(obj, rq);
  
        // Display message
        System.out.println(
            "-> Trying to retreive 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);
        }
    }
}


输出
-> 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

示例 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 rq = new ReferenceQueue();
  
        // Creating an object of PhantomReference class
        // of X class type with RefereneQueue object
        // reference queue
        PhantomReference phantomobj
            = new PhantomReference(obj, rq);
  
        // Display message
        System.out.println(
            "-> Trying to retreive 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 retreiive object from Phantom Reference :
java.lang.NullPointerException