Originally stated at http://cs.oswego.edu/pipermail/concurrency-interest/2012-August/009653.html Running with test: import java.lang.ref.*; public class WeakReferenceTest { private static Object str = new Object() { public String toString() { return "The Object"; } protected void finalize() throws Throwable { System.out.println("The Object is being finalized"); super.finalize(); } }; private final static ReferenceQueue<Object> rq = new ReferenceQueue<Object>(); private final static WeakReference<Object> wr = new WeakReference<Object>(str, rq); public static void main(String[] args) throws InterruptedException { Thread reader = new Thread() { public void run() { while (wr.get() != null) { } System.out.println("wr.get() returned null"); } }; Thread queueReader = new Thread() { public void run() { try { Reference<? extends Object> ref = rq.remove(); System.out.println(ref); System.out.println("queueReader returned, ref==wr is " + (ref == wr)); } catch (InterruptedException e) { System.err.println("Sleep interrupted - exiting"); } } }; reader.start(); queueReader.start(); Thread.sleep(1000); str = null; System.gc(); } } Output with Server HotSpot: The Object is being finalized java.lang.ref.WeakReference@72ebbf5c queueReader returned, ref==wr is true -- VM does not end Output with Client HotSpot: The Object is being finalized wr.get() returned null java.lang.ref.WeakReference@110769b queueReader returned, ref==wr is true -------------------------------------------- The disassembly shows C2 had inlined WeakReference.get(), stored WeakReference.refent in local, and reduced the loop in readerThread to infinite version. Then, readerThread had lost the notification about the WeakReference clearance. There are two options with regards to this: a. Mark $referent in WeakReference (and other References) as volatile. This will break the C2 hoisting. The downside is requiring volatile write in constructor which might have unexpected performance impact in most code. b. Enable C2 to treat $referent as special field being updated by GC, and exempt it from caching in local, re-reading the field every time (or at least each loop iteration, if that is possible with compiler infrastructure). c. Other?
|