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 java.util.HashMap;
  29 import java.util.Map;
  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<S> extends ReferenceQueue<S> {
  47         boolean enqueue(Reference<? extends S> r) {
  48             return false;
  49         }
  50     }
  51 
  52     static class mutableInt {
  53         private int value = 1;
  54 
  55         public void increment(){ value += 1; }
  56         public int getValue(){ return value; }
  57         public int compareTo(mutableInt e){ return getValue() - e.getValue(); }
  58 
  59         public String toString(){ return Integer.toString(value); }
  60     }
  61 
  62     static ReferenceQueue<Object> NULL = new Null<>();
  63     static ReferenceQueue<Object> ENQUEUED = new Null<>();
  64 
  65     static private class Lock { };
  66     private Lock lock = new Lock();
  67     private volatile Reference<? extends T> head = null;
  68     private long queueLength = 0;
  69 
  70     boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */
  71         synchronized (lock) {
  72             // Check that since getting the lock this reference hasn't already been
  73             // enqueued (and even then removed)
  74             ReferenceQueue<?> queue = r.queue;
  75             if ((queue == NULL) || (queue == ENQUEUED)) {
  76                 return false;
  77             }
  78             assert queue == this;
  79             r.queue = ENQUEUED;
  80             r.next = (head == null) ? r : head;
  81             head = r;
  82             queueLength++;
  83             if (r instanceof FinalReference) {
  84                 sun.misc.VM.addFinalRefCount(1);
  85             }
  86             lock.notifyAll();
  87             return true;
  88         }
  89     }
  90 
  91     @SuppressWarnings("unchecked")
  92     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
  93         Reference<? extends T> r = head;
  94         if (r != null) {
  95             head = (r.next == r) ?
  96                 null :
  97                 r.next; // Unchecked due to the next field having a raw type in Reference
  98             r.queue = NULL;
  99             r.next = r;
 100             queueLength--;
 101             if (r instanceof FinalReference) {
 102                 sun.misc.VM.addFinalRefCount(-1);
 103             }
 104             return r;
 105         }
 106         return null;
 107     }
 108 
 109     /**
 110      * Polls this queue to see if a reference object is available.  If one is
 111      * available without further delay then it is removed from the queue and
 112      * returned.  Otherwise this method immediately returns <tt>null</tt>.
 113      *
 114      * @return  A reference object, if one was immediately available,
 115      *          otherwise <code>null</code>
 116      */
 117     public Reference<? extends T> poll() {
 118         if (head == null)
 119             return null;
 120         synchronized (lock) {
 121             return reallyPoll();
 122         }
 123     }
 124 
 125     /**
 126      * Iterate queue and cout the number of instances of each object type pending finalization
 127      *
 128      * @return Map of object types with associated counts
 129      */
 130     @SuppressWarnings("unchecked")
 131     public Map<String, mutableInt> countInstances() {
 132         if (head == null) {
 133             return null;
 134         }
 135 
 136         HashMap<String, mutableInt> countMap = new HashMap<>();
 137 
 138         synchronized (lock) {
 139             Reference<? extends T> r = head;
 140             if (r != null) {
 141                 Object referent = r.get();
 142                 if (referent != null) {
 143                     String typeName = referent.getClass().getName();
 144                     mutableInt v = countMap.get(typeName);
 145                     if (v == null) {
 146                       countMap.put(typeName, new mutableInt());
 147                     }
 148                     else {
 149                         v.increment();
 150                     }
 151                 }
 152                 r = r.next;
 153             }
 154         }
 155 
 156         return countMap;
 157     }
 158 
 159 
 160     /**
 161      * Removes the next reference object in this queue, blocking until either
 162      * one becomes available or the given timeout period expires.
 163      *
 164      * <p> This method does not offer real-time guarantees: It schedules the
 165      * timeout as if by invoking the {@link Object#wait(long)} method.
 166      *
 167      * @param  timeout  If positive, block for up to <code>timeout</code>
 168      *                  milliseconds while waiting for a reference to be
 169      *                  added to this queue.  If zero, block indefinitely.
 170      *
 171      * @return  A reference object, if one was available within the specified
 172      *          timeout period, otherwise <code>null</code>
 173      *
 174      * @throws  IllegalArgumentException
 175      *          If the value of the timeout argument is negative
 176      *
 177      * @throws  InterruptedException
 178      *          If the timeout wait is interrupted
 179      */
 180     public Reference<? extends T> remove(long timeout)
 181         throws IllegalArgumentException, InterruptedException
 182     {
 183         if (timeout < 0) {
 184             throw new IllegalArgumentException("Negative timeout value");
 185         }
 186         synchronized (lock) {
 187             Reference<? extends T> r = reallyPoll();
 188             if (r != null) return r;
 189             long start = (timeout == 0) ? 0 : System.nanoTime();
 190             for (;;) {
 191                 lock.wait(timeout);
 192                 r = reallyPoll();
 193                 if (r != null) return r;
 194                 if (timeout != 0) {
 195                     long end = System.nanoTime();
 196                     timeout -= (end - start) / 1000_000;
 197                     if (timeout <= 0) return null;
 198                     start = end;
 199                 }
 200             }
 201         }
 202     }
 203 
 204     /**
 205      * Removes the next reference object in this queue, blocking until one
 206      * becomes available.
 207      *
 208      * @return A reference object, blocking until one becomes available
 209      * @throws  InterruptedException  If the wait is interrupted
 210      */
 211     public Reference<? extends T> remove() throws InterruptedException {
 212         return remove(0);
 213     }
 214 
 215 }