1 /*
   2  * Copyright (c) 1997, 2013, 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 static java.util.concurrent.TimeUnit.*;
  29 
  30 /**
  31  * Reference queues, to which registered reference objects are appended by the
  32  * garbage collector after the appropriate reachability changes are detected.
  33  *
  34  * @author   Mark Reinhold
  35  * @since    1.2
  36  */
  37 
  38 public class ReferenceQueue<T> {
  39 
  40     /**
  41      * Constructs a new reference-object queue.
  42      */
  43     public ReferenceQueue() { }
  44 
  45     private static class Null<S> extends ReferenceQueue<S> {
  46         boolean enqueue(Reference<? extends S> r) {
  47             return false;
  48         }
  49     }
  50 
  51     static ReferenceQueue<Object> NULL = new Null<>();
  52     static ReferenceQueue<Object> ENQUEUED = new Null<>();
  53 
  54     static private class Lock { };
  55     private Lock lock = new Lock();
  56     private volatile Reference<? extends T> head = null;
  57     private long queueLength = 0;
  58 
  59     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
  60         synchronized (lock) {
  61             // Check that since getting the lock this reference hasn't already been
  62             // enqueued (and even then removed)
  63             ReferenceQueue<?> queue = r.queue;
  64             if ((queue == NULL) || (queue == ENQUEUED)) {
  65                 return false;
  66             }
  67             assert queue == this;
  68             r.queue = ENQUEUED;
  69             r.next = (head == null) ? r : head;
  70             head = r;
  71             queueLength++;
  72             if (r instanceof FinalReference) {
  73                 sun.misc.VM.addFinalRefCount(1);
  74             }
  75             lock.notifyAll();
  76             return true;
  77         }
  78     }
  79 
  80     @SuppressWarnings("unchecked")
  81     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
  82         Reference<? extends T> r = head;
  83         if (r != null) {
  84             head = (r.next == r) ?
  85                 null :
  86                 r.next; // Unchecked due to the next field having a raw type in Reference
  87             r.queue = NULL;
  88             r.next = r;
  89             queueLength--;
  90             if (r instanceof FinalReference) {
  91                 sun.misc.VM.addFinalRefCount(-1);
  92             }
  93             return r;
  94         }
  95         return null;
  96     }
  97 
  98     /**
  99      * Polls this queue to see if a reference object is available.  If one is
 100      * available without further delay then it is removed from the queue and
 101      * returned.  Otherwise this method immediately returns <tt>null</tt>.
 102      *
 103      * @return  A reference object, if one was immediately available,
 104      *          otherwise <code>null</code>
 105      */
 106     public Reference<? extends T> poll() {
 107         if (head == null)
 108             return null;
 109         synchronized (lock) {
 110             return reallyPoll();
 111         }
 112     }
 113 
 114     /**
 115      * Removes the next reference object in this queue, blocking until either
 116      * one becomes available or the given timeout period expires.
 117      *
 118      * <p> This method does not offer real-time guarantees: It schedules the
 119      * timeout as if by invoking the {@link Object#wait(long)} method.
 120      *
 121      * @param  timeout  If positive, block for up to <code>timeout</code>
 122      *                  milliseconds while waiting for a reference to be
 123      *                  added to this queue.  If zero, block indefinitely.
 124      *
 125      * @return  A reference object, if one was available within the specified
 126      *          timeout period, otherwise <code>null</code>
 127      *
 128      * @throws  IllegalArgumentException
 129      *          If the value of the timeout argument is negative
 130      *
 131      * @throws  InterruptedException
 132      *          If the timeout wait is interrupted
 133      */
 134     public Reference<? extends T> remove(long timeout)
 135         throws IllegalArgumentException, InterruptedException
 136     {
 137         if (timeout < 0) {
 138             throw new IllegalArgumentException("Negative timeout value");
 139         }
 140         synchronized (lock) {
 141             Reference<? extends T> r = reallyPoll();
 142             if (r != null) return r;
 143             long start = (timeout == 0) ? 0 : System.nanoTime();
 144             for (;;) {
 145                 lock.wait(timeout);
 146                 r = reallyPoll();
 147                 if (r != null) return r;
 148                 if (timeout != 0) {
 149                     long end = System.nanoTime();
 150                     timeout -= NANOSECONDS.toMillis(end - start);
 151                     if (timeout <= 0) return null;
 152                     start = end;
 153                 }
 154             }
 155         }
 156     }
 157 
 158     /**
 159      * Removes the next reference object in this queue, blocking until one
 160      * becomes available.
 161      *
 162      * @return A reference object, blocking until one becomes available
 163      * @throws  InterruptedException  If the wait is interrupted
 164      */
 165     public Reference<? extends T> remove() throws InterruptedException {
 166         return remove(0);
 167     }
 168 
 169 }