GC 期间未释放幻象引用

Phantom reference not freed up during GC

我对虚引用的用法有点困惑。我读到,只要垃圾收集器喜欢,就可以收集只有 Phantom 引用指向它们的对象。但是,它在我的示例中没有按预期工作。

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.HashMap;
import java.util.Map;


public class ClassTest {
    private static Thread m_collector;
    private static boolean m_stopped = false;
    private static final ReferenceQueue refque = new ReferenceQueue();
    Map<Reference,String> cleanUpMap = new HashMap<Reference,String>();


    public void startThread() {
        m_collector = new Thread() {
            public void run() {
                while (!m_stopped) {
                    try {
                            Reference ref = refque.remove(1000);
                            System.out.println(" Timeout ");
                                                if (null != ref) {
                            System.out.println(" ref not null ");

                        }
                    } catch (Exception ex) {
                        break;
                    }
                }
            }
        };
        m_collector.setDaemon(true);
        m_collector.start();
    }

    public void register() {
        System.out.println("Creating phantom references");

        class Referred {
                }

          Referred strong = new Referred();
          PhantomReference<Referred> pref = new PhantomReference(strong, refque);
    //    cleanUpMap.put(pref, "Free up resources");
          strong = null;

    }



public static void collect() throws InterruptedException {
    System.out.println("GC called");
    System.gc();
    System.out.println("Sleeping");
    Thread.sleep(5000);
}

public static void main(String args[]) throws InterruptedException {
    ClassTest test= new ClassTest();
    test.startThread();

    test.register();
    test.collect();
    m_stopped = true;
    System.out.println("Done");
}

}

在上面的示例中,当我 运行 时,我看到对象 "strong" 没有被自动垃圾回收。我预计当 "strong" 对象被分配给 null 时,该对象会自动被垃圾收集。奇怪的是,只有当我在 register 函数中取消注释以下行时,它才会被垃圾收集。

 //cleanUpMap.put(pref, "Free up resources");" 

这背后的原因是什么?但是,如果我在 Main 函数本身中创建幻像引用,则不会出现此问题。换句话说,当 "strong" 在 main 函数中被分配给 null 时,对象会被自动垃圾回收,如下面的代码所示。

public static void main(String args[]) throws InterruptedException {
    System.out.println("Creating phantom references");

    // The reference itself will be appended to the dead queue for clean up.
    ReferenceQueue dead = new ReferenceQueue(); 

    PhantomReference<Referred> phantom = new PhantomReference(strong, dead);


    strong = null;

    // The object may now be collected
    System.out.println("Suggesting collection");
    System.gc();
    System.out.println("Sleeping");
    Thread.sleep(5000);

    // Check for 
    Reference reference = dead.poll();
    if (reference != null) {
        System.out.println("not null");
    }
    System.out.println("Done");
}  

为什么两种情况下的行为不同?

您的幻象引用是一个普通的 Java 对象,如果无法访问,它将被垃圾回收。

如果幻象引用是在引用对象之前或在同一个集合中收集的,则不会将其添加到引用队列。

将所有幻象引用放在一个集合中可以防止引用被过早地垃圾回收。

通常您需要专门收集未处理的幻象引用以及引用队列。

您可以在 this article.

中找到基于 post mortem 清理实现幻像引用的示例