src/share/classes/java/lang/ref/ReferenceQueue.java

Print this page

        

@@ -56,10 +56,17 @@
 
     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
         synchronized (r) {
             if (r.queue == ENQUEUED) return false;
             synchronized (lock) {
+                // There is a race between this method and the polling: it may occur
+                // that one thread just successfully removed a Reference from the queue,
+                // making it inactive, and another thread calling this method on this
+                // queue with the same Reference instance. Filter out those attempts.
+                if (r.queue != this) {
+                    return false;
+                }
                 r.queue = ENQUEUED;
                 r.next = (head == null) ? r : head;
                 head = r;
                 queueLength++;
                 if (r instanceof FinalReference) {