1 /*
   2  * Copyright (c) 1997, 2015, 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 
  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     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
  81         Reference<? extends T> r = head;
  82         if (r != null) {
  83             @SuppressWarnings("unchecked")
  84             Reference<? extends T> rn = r.next;
  85             head = (rn == r) ? null : rn;
  86             r.queue = NULL;
  87             r.next = r;
  88             queueLength--;
  89             if (r instanceof FinalReference) {
  90                 sun.misc.VM.addFinalRefCount(-1);
  91             }
  92             return r;
  93         }
  94         return null;
  95     }
  96 
  97     /**
  98      * Polls this queue to see if a reference object is available.  If one is
  99      * available without further delay then it is removed from the queue and
 100      * returned.  Otherwise this method immediately returns <tt>null</tt>.
 101      *
 102      * @return  A reference object, if one was immediately available,
 103      *          otherwise <code>null</code>
 104      */
 105     public Reference<? extends T> poll() {
 106         if (head == null)
 107             return null;
 108         synchronized (lock) {
 109             return reallyPoll();
 110         }
 111     }
 112 
 113     /**
 114      * Removes the next reference object in this queue, blocking until either
 115      * one becomes available or the given timeout period expires.
 116      *
 117      * <p> This method does not offer real-time guarantees: It schedules the
 118      * timeout as if by invoking the {@link Object#wait(long)} method.
 119      *
 120      * @param  timeout  If positive, block for up to <code>timeout</code>
 121      *                  milliseconds while waiting for a reference to be
 122      *                  added to this queue.  If zero, block indefinitely.
 123      *
 124      * @return  A reference object, if one was available within the specified
 125      *          timeout period, otherwise <code>null</code>
 126      *
 127      * @throws  IllegalArgumentException
 128      *          If the value of the timeout argument is negative
 129      *
 130      * @throws  InterruptedException
 131      *          If the timeout wait is interrupted
 132      */
 133     public Reference<? extends T> remove(long timeout)
 134         throws IllegalArgumentException, InterruptedException
 135     {
 136         if (timeout < 0) {
 137             throw new IllegalArgumentException("Negative timeout value");
 138         }
 139         synchronized (lock) {
 140             Reference<? extends T> r = reallyPoll();
 141             if (r != null) return r;
 142             long start = (timeout == 0) ? 0 : System.nanoTime();
 143             for (;;) {
 144                 lock.wait(timeout);
 145                 r = reallyPoll();
 146                 if (r != null) return r;
 147                 if (timeout != 0) {
 148                     long end = System.nanoTime();
 149                     timeout -= (end - start) / 1000_000;
 150                     if (timeout <= 0) return null;
 151                     start = end;
 152                 }
 153             }
 154         }
 155     }
 156 
 157     /**
 158      * Removes the next reference object in this queue, blocking until one
 159      * becomes available.
 160      *
 161      * @return A reference object, blocking until one becomes available
 162      * @throws  InterruptedException  If the wait is interrupted
 163      */
 164     public Reference<? extends T> remove() throws InterruptedException {
 165         return remove(0);
 166     }
 167 
 168     /**
 169      * Iterate queue and invoke given action with each Reference.
 170      * Suitable for diagnostic purposes.
 171      * WARNING: any use of this method should make sure to not
 172      * retain the referents of iterated references (in case of
 173      * FinalReference(s)) so that their life is not prolonged more
 174      * than necessary.
 175      */
 176     void forEach(Consumer<? super Reference<? extends T>> action) {
 177         for (Reference<? extends T> r = head; r != null;) {
 178             action.accept(r);
 179             @SuppressWarnings("unchecked")
 180             Reference<? extends T> rn = r.next;
 181             if (rn == r) {
 182                 if (r.queue == ENQUEUED) {
 183                     // still enqueued -> we reached end of chain
 184                     r = null;
 185                 } else {
 186                     // already dequeued: r.queue == NULL; ->
 187                     // restart from head when overtaken by queue poller(s)
 188                     r = head;
 189                 }
 190             } else {
 191                 // next in chain
 192                 r = rn;
 193             }
 194         }
 195     }
 196 }