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