< prev index next >

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

Print this page

  1 /*
  2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.ref;
 27 



 28 import java.util.function.Consumer;
 29 import jdk.internal.misc.VM;
 30 
 31 /**
 32  * Reference queues, to which registered reference objects are appended by the
 33  * garbage collector after the appropriate reachability changes are detected.
 34  *
 35  * @author   Mark Reinhold
 36  * @since    1.2
 37  */
 38 
 39 public class ReferenceQueue<T> {
 40 
 41     /**
 42      * Constructs a new reference-object queue.
 43      */
 44     public ReferenceQueue() { }
 45 
 46     private static class Null extends ReferenceQueue<Object> {



 47         boolean enqueue(Reference<?> r) {
 48             return false;
 49         }
 50     }
 51 
 52     static final ReferenceQueue<Object> NULL = new Null();
 53     static final ReferenceQueue<Object> ENQUEUED = new Null();
 54 
 55     private static class Lock { };
 56     private final Lock lock = new Lock();
 57     private volatile Reference<? extends T> head;
 58     private long queueLength = 0;
 59 
 60     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
 61         synchronized (lock) {
 62             // Check that since getting the lock this reference hasn't already been
 63             // enqueued (and even then removed)
 64             ReferenceQueue<?> queue = r.queue;
 65             if ((queue == NULL) || (queue == ENQUEUED)) {
 66                 return false;
 67             }
 68             assert queue == this;
 69             // Self-loop end, so if a FinalReference it remains inactive.
 70             r.next = (head == null) ? r : head;
 71             head = r;
 72             queueLength++;
 73             // Update r.queue *after* adding to list, to avoid race
 74             // with concurrent enqueued checks and fast-path poll().
 75             // Volatiles ensure ordering.
 76             r.queue = ENQUEUED;
 77             if (r instanceof FinalReference) {
 78                 VM.addFinalRefCount(1);
 79             }
 80             lock.notifyAll();
 81             return true;






 82         }














 83     }
 84 
 85     private Reference<? extends T> reallyPoll() {       /* Must hold lock */




 86         Reference<? extends T> r = head;
 87         if (r != null) {
 88             r.queue = NULL;
 89             // Update r.queue *before* removing from list, to avoid
 90             // race with concurrent enqueued checks and fast-path
 91             // poll().  Volatiles ensure ordering.
 92             @SuppressWarnings("unchecked")
 93             Reference<? extends T> rn = r.next;
 94             // Handle self-looped next as end of list designator.
 95             head = (rn == r) ? null : rn;
 96             // Self-loop next rather than setting to null, so if a
 97             // FinalReference it remains inactive.
 98             r.next = r;
 99             queueLength--;
100             if (r instanceof FinalReference) {
101                 VM.addFinalRefCount(-1);
102             }
103             return r;
104         }
105         return null;
106     }
107 


































108     /**
109      * Polls this queue to see if a reference object is available.  If one is
110      * available without further delay then it is removed from the queue and
111      * returned.  Otherwise this method immediately returns {@code null}.
112      *
113      * @return  A reference object, if one was immediately available,
114      *          otherwise {@code null}
115      */
116     public Reference<? extends T> poll() {
117         if (head == null)
118             return null;
119         synchronized (lock) {
120             return reallyPoll();



121         }
122     }
123 
124     /**
125      * Removes the next reference object in this queue, blocking until either
126      * one becomes available or the given timeout period expires.
127      *
128      * <p> This method does not offer real-time guarantees: It schedules the
129      * timeout as if by invoking the {@link Object#wait(long)} method.
130      *
131      * @param  timeout  If positive, block for up to {@code timeout}
132      *                  milliseconds while waiting for a reference to be
133      *                  added to this queue.  If zero, block indefinitely.
134      *
135      * @return  A reference object, if one was available within the specified
136      *          timeout period, otherwise {@code null}
137      *
138      * @throws  IllegalArgumentException
139      *          If the value of the timeout argument is negative
140      *
141      * @throws  InterruptedException
142      *          If the timeout wait is interrupted
143      */
144     public Reference<? extends T> remove(long timeout)
145         throws IllegalArgumentException, InterruptedException
146     {
147         if (timeout < 0) {
148             throw new IllegalArgumentException("Negative timeout value");
149         }
150         synchronized (lock) {
151             Reference<? extends T> r = reallyPoll();
152             if (r != null) return r;
153             long start = (timeout == 0) ? 0 : System.nanoTime();
154             for (;;) {
155                 lock.wait(timeout);
156                 r = reallyPoll();
157                 if (r != null) return r;
158                 if (timeout != 0) {
159                     long end = System.nanoTime();
160                     timeout -= (end - start) / 1000_000;
161                     if (timeout <= 0) return null;
162                     start = end;
163                 }
164             }
165         }
166     }
167 
168     /**
169      * Removes the next reference object in this queue, blocking until one
170      * becomes available.
171      *
172      * @return A reference object, blocking until one becomes available
173      * @throws  InterruptedException  If the wait is interrupted
174      */
175     public Reference<? extends T> remove() throws InterruptedException {
176         return remove(0);





177     }
178 
179     /**
180      * Iterate queue and invoke given action with each Reference.
181      * Suitable for diagnostic purposes.
182      * WARNING: any use of this method should make sure to not
183      * retain the referents of iterated references (in case of
184      * FinalReference(s)) so that their life is not prolonged more
185      * than necessary.
186      */
187     void forEach(Consumer<? super Reference<? extends T>> action) {
188         for (Reference<? extends T> r = head; r != null;) {
189             action.accept(r);
190             @SuppressWarnings("unchecked")
191             Reference<? extends T> rn = r.next;
192             if (rn == r) {
193                 if (r.queue == ENQUEUED) {
194                     // still enqueued -> we reached end of chain
195                     r = null;
196                 } else {

  1 /*
  2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.ref;
 27 
 28 import java.util.concurrent.TimeUnit;
 29 import java.util.concurrent.locks.Condition;
 30 import java.util.concurrent.locks.ReentrantLock;
 31 import java.util.function.Consumer;
 32 import jdk.internal.misc.VM;
 33 
 34 /**
 35  * Reference queues, to which registered reference objects are appended by the
 36  * garbage collector after the appropriate reachability changes are detected.
 37  *
 38  * @author   Mark Reinhold
 39  * @since    1.2
 40  */
 41 
 42 public class ReferenceQueue<T> {






 43     private static class Null extends ReferenceQueue<Object> {
 44         public Null() { super(0); }
 45         
 46         @Override 
 47         boolean enqueue(Reference<?> r) {
 48             return false;
 49         }
 50     }
 51 
 52     static final ReferenceQueue<Object> NULL = new Null();
 53     static final ReferenceQueue<Object> ENQUEUED = new Null();
 54 


 55     private volatile Reference<? extends T> head;
 56     private long queueLength = 0;
 57 
 58     private final ReentrantLock lock;
 59     private final Condition notEmpty;
 60 
 61     void signal() { notEmpty.signalAll(); }
 62     void await() throws InterruptedException { notEmpty.await(); }
 63     void await(long timeoutMillis) throws InterruptedException { 
 64         notEmpty.await(timeoutMillis, TimeUnit.MILLISECONDS);
 65     }
 66 
 67     /**
 68      * Constructs a new reference-object queue.
 69      */
 70     public ReferenceQueue() {
 71         this.lock = new ReentrantLock();
 72         this.notEmpty = lock.newCondition();
 73     }
 74 
 75     ReferenceQueue(int dummy) {
 76         this.lock = null;
 77         this.notEmpty = null;
 78     }
 79 
 80     final boolean enqueue0(Reference<? extends T> r) { // must hold lock
 81         // Check that since getting the lock this reference hasn't already been
 82         // enqueued (and even then removed)
 83         ReferenceQueue<?> queue = r.queue;
 84         if ((queue == NULL) || (queue == ENQUEUED)) {
 85             return false;
 86         }
 87         assert queue == this;
 88         // Self-loop end, so if a FinalReference it remains inactive.
 89         r.next = (head == null) ? r : head;
 90         head = r;
 91         queueLength++;
 92         // Update r.queue *after* adding to list, to avoid race
 93         // with concurrent enqueued checks and fast-path poll().
 94         // Volatiles ensure ordering.
 95         r.queue = ENQUEUED;
 96         if (r instanceof FinalReference) {
 97             VM.addFinalRefCount(1);
 98         }
 99         signal();
100         return true;
101     }
102 
103     final boolean headIsNull() {
104         return head == null;
105     }
106     
107     final Reference<? extends T> poll0() { // must hold lock
108         Reference<? extends T> r = head;
109         if (r != null) {
110             r.queue = NULL;
111             // Update r.queue *before* removing from list, to avoid
112             // race with concurrent enqueued checks and fast-path
113             // poll().  Volatiles ensure ordering.
114             @SuppressWarnings("unchecked")
115             Reference<? extends T> rn = r.next;
116             // Handle self-looped next as end of list designator.
117             head = (rn == r) ? null : rn;
118             // Self-loop next rather than setting to null, so if a
119             // FinalReference it remains inactive.
120             r.next = r;
121             queueLength--;
122             if (r instanceof FinalReference) {
123                 VM.addFinalRefCount(-1);
124             }
125             return r;
126         }
127         return null;
128     }
129 
130     final Reference<? extends T> remove0(long timeout) 
131             throws IllegalArgumentException, InterruptedException { // must hold lock
132         Reference<? extends T> r = poll0();
133         if (r != null) return r;
134         long start = System.nanoTime();
135         for (;;) {
136             await(timeout);
137             r = poll0();
138             if (r != null) return r;
139 
140             long end = System.nanoTime();
141             timeout -= (end - start) / 1000_000;
142             if (timeout <= 0) return null;
143             start = end;
144         }
145     }
146 
147     final Reference<? extends T> remove0() throws InterruptedException { // must hold lock
148         for (;;) {
149             var r = poll0();
150             if (r != null) return r;
151             await();
152         }
153     }
154 
155     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
156         lock.lock();
157         try {
158             return enqueue0(r);
159         } finally {
160             lock.unlock();
161         }
162     }
163 
164     /**
165      * Polls this queue to see if a reference object is available.  If one is
166      * available without further delay then it is removed from the queue and
167      * returned.  Otherwise this method immediately returns {@code null}.
168      *
169      * @return  A reference object, if one was immediately available,
170      *          otherwise {@code null}
171      */
172     public Reference<? extends T> poll() {
173         if (headIsNull())
174             return null;
175         lock.lock();
176         try {
177             return poll0();
178         } finally {
179             lock.unlock();
180         }
181     }
182 
183     /**
184      * Removes the next reference object in this queue, blocking until either
185      * one becomes available or the given timeout period expires.
186      *
187      * <p> This method does not offer real-time guarantees: It schedules the
188      * timeout as if by invoking the {@link Object#wait(long)} method.
189      *
190      * @param  timeout  If positive, block for up to {@code timeout}
191      *                  milliseconds while waiting for a reference to be
192      *                  added to this queue.  If zero, block indefinitely.
193      *
194      * @return  A reference object, if one was available within the specified
195      *          timeout period, otherwise {@code null}
196      *
197      * @throws  IllegalArgumentException
198      *          If the value of the timeout argument is negative
199      *
200      * @throws  InterruptedException
201      *          If the timeout wait is interrupted
202      */
203     public Reference<? extends T> remove(long timeout) 
204         throws IllegalArgumentException, InterruptedException {
205         if (timeout < 0) throw new IllegalArgumentException("Negative timeout value");
206         if (timeout == 0) return remove();
207 
208         lock.lock();
209         try {
210             return remove0(timeout);
211         } finally {
212             lock.unlock();











213         }
214     }
215 
216     /**
217      * Removes the next reference object in this queue, blocking until one
218      * becomes available.
219      *
220      * @return A reference object, blocking until one becomes available
221      * @throws  InterruptedException  If the wait is interrupted
222      */
223     public Reference<? extends T> remove() throws InterruptedException {
224         lock.lock();
225         try {
226             return remove0();
227         } finally {
228             lock.unlock();
229         }
230     }
231 
232     /**
233      * Iterate queue and invoke given action with each Reference.
234      * Suitable for diagnostic purposes.
235      * WARNING: any use of this method should make sure to not
236      * retain the referents of iterated references (in case of
237      * FinalReference(s)) so that their life is not prolonged more
238      * than necessary.
239      */
240     void forEach(Consumer<? super Reference<? extends T>> action) {
241         for (Reference<? extends T> r = head; r != null;) {
242             action.accept(r);
243             @SuppressWarnings("unchecked")
244             Reference<? extends T> rn = r.next;
245             if (rn == r) {
246                 if (r.queue == ENQUEUED) {
247                     // still enqueued -> we reached end of chain
248                     r = null;
249                 } else {
< prev index next >