Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is still there. I tested it with Java 8 and could prove it.</p> <p>You should note the following things:</p> <ol> <li><p>The only way to force a guaranteed garbage collection is to try an allocation which ends in an OutOfMemoryError as the JVM is required to try freeing unused objects before throwing. This however does not hold if the requested amount is too large to ever succeed, i.e. excesses the address space. Trying to raise the allocation until getting an OOME is a good strategy.</p></li> <li><p>The guaranteed GC described in Point 1 does not guaranty a finalization. The time when finalize() methods are invoked is not specified, they might be never called at all. So adding a finalize() method to a class might prevent its instances from being collected, so finalize is not a good choice to analyse GC behavior.</p></li> <li><p>Creating another new local variable after a local variable went out of scope will reuse its place in the stack frame. In the following example, object a will be collected as its place in the stack frame is occupied by the local variable b. But b last until the end of the main method as there is no other local variable to occupy its place.</p> <pre><code>import java.lang.ref.*; public class Test { static final ReferenceQueue&lt;Object&gt; RQ=new ReferenceQueue&lt;&gt;(); static Reference&lt;Object&gt; A, B; public static void main(String[] s) { { Object a=new Object(); A=new PhantomReference&lt;&gt;(a, RQ); } { Object b=new Object(); B=new PhantomReference&lt;&gt;(b, RQ); } forceGC(); checkGC(); } private static void forceGC() { try { for(int i=100000;;i+=i) { byte[] b=new byte[i]; } } catch(OutOfMemoryError err){ err.printStackTrace();} } private static void checkGC() { for(;;) { Reference&lt;?&gt; r=RQ.poll(); if(r==null) break; if(r==A) System.out.println("Object a collected"); if(r==B) System.out.println("Object b collected"); } } } </code></pre></li> </ol>
 

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