Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy PhantomReference does not work?
    text
    copied!<p>Demo code:</p> <pre><code>import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class Main { public static void main(String[] args) throws InterruptedException { Object test = new Object(); ReferenceQueue&lt;Object&gt; q = new ReferenceQueue&lt;Object&gt;(); PhantomReference&lt;Object&gt; p = new PhantomReference&lt;Object&gt;(test, q); Object lock = new Object(); while (true) { synchronized (lock) { //q.poll() is null always,why? if (q.poll() != null) { break; } //System.gc(); lock.wait(); } } System.out.println(1111111); } } </code></pre> <p>I tested the code,but it always is dead loop. The code (System.out.println(1111111);) can not execute,q.poll() reurn null.</p> <p>I think if test object is removed by GC,q.poll() will return p object,then break loop,but invoke this demo code,it is not like my thought </p> <p>Edited: I modify the demo code,it can work now.</p> <pre><code>import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class Main { public static void main(String[] args) throws InterruptedException { Object test = new Object(); ReferenceQueue&lt;Object&gt; q = new ReferenceQueue&lt;Object&gt;(); PhantomReference&lt;Object&gt; p = new PhantomReference&lt;Object&gt;(test, q); Object lock = new Object(); while (true) { synchronized (lock) { if (q.poll() != null) { break; } test = null; //it is important System.gc(); lock.wait(100);//should not lock.wait() } } System.out.println(1111111); } } </code></pre> <p>AS sb says,the statement( test=null) is key.GC collect test object that assign null.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload