Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy PhantomReference does not work?
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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