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 sun.misc.Cleaner; 29 import sun.misc.JavaLangRefAccess; 30 import sun.misc.ManagedLocalsThread; 31 import sun.misc.SharedSecrets; 32 33 /** 34 * Abstract base class for reference objects. This class defines the 35 * operations common to all reference objects. Because reference objects are 36 * implemented in close cooperation with the garbage collector, this class may 37 * not be subclassed directly. 38 * 39 * @author Mark Reinhold 40 * @since 1.2 41 */ 42 43 public abstract class Reference<T> { 44 45 /* A Reference instance is in one of four possible internal states: 46 * 47 * Active: Subject to special treatment by the garbage collector. Some 48 * time after the collector detects that the reachability of the 49 * referent has changed to the appropriate state, it changes the 50 * instance's state to either Pending or Inactive, depending upon 51 * whether or not the instance was registered with a queue when it was 52 * created. In the former case it also adds the instance to the 53 * pending-Reference list. Newly-created instances are Active. 54 * 55 * Pending: An element of the pending-Reference list, waiting to be 56 * enqueued by the Reference-handler thread. Unregistered instances 57 * are never in this state. 58 * 59 * Enqueued: An element of the queue with which the instance was 60 * registered when it was created. When an instance is removed from 61 * its ReferenceQueue, it is made Inactive. Unregistered instances are 62 * never in this state. 63 * 64 * Inactive: Nothing more to do. Once an instance becomes Inactive its 65 * state will never change again. 66 * 67 * The state is encoded in the queue and next fields as follows: 68 * 69 * Active: queue = ReferenceQueue with which instance is registered, or 70 * ReferenceQueue.NULL if it was not registered with a queue; next = 71 * null. 72 * 73 * Pending: queue = ReferenceQueue with which instance is registered; 74 * next = this 75 * 76 * Enqueued: queue = ReferenceQueue.ENQUEUED; next = Following instance 77 * in queue, or this if at end of list. 78 * 79 * Inactive: queue = ReferenceQueue.NULL; next = this. 80 * 81 * With this scheme the collector need only examine the next field in order 82 * to determine whether a Reference instance requires special treatment: If 83 * the next field is null then the instance is active; if it is non-null, 84 * then the collector should treat the instance normally. 85 * 86 * To ensure that a concurrent collector can discover active Reference 87 * objects without interfering with application threads that may apply 88 * the enqueue() method to those objects, collectors should link 89 * discovered objects through the discovered field. The discovered 90 * field is also used for linking Reference objects in the pending list. 91 */ 92 93 private T referent; /* Treated specially by GC */ 94 95 volatile ReferenceQueue<? super T> queue; 96 97 /* When active: NULL 98 * pending: this 99 * Enqueued: next reference in queue (or this if last) 100 * Inactive: this 101 */ 102 @SuppressWarnings("rawtypes") 103 Reference next; 104 105 /* When active: next element in a discovered reference list maintained by GC (or this if last) 106 * pending: next element in the pending list (or null if last) 107 * otherwise: NULL 108 */ 109 transient private Reference<T> discovered; /* used by VM */ 110 111 112 /* Object used to synchronize with the garbage collector. The collector 113 * must acquire this lock at the beginning of each collection cycle. It is 114 * therefore critical that any code holding this lock complete as quickly 115 * as possible, allocate no new objects, and avoid calling user code. 116 */ 117 static private class Lock { } 118 private static Lock lock = new Lock(); 119 120 121 /* List of References waiting to be enqueued. The collector adds 122 * References to this list, while the Reference-handler thread removes 123 * them. This list is protected by the above lock object. The 124 * list uses the discovered field to link its elements. 125 */ 126 private static Reference<Object> pending = null; 127 128 /* High-priority thread to enqueue pending References 129 */ 130 private static class ReferenceHandler extends ManagedLocalsThread { 131 132 private static void ensureClassInitialized(Class<?> clazz) { 133 try { 134 Class.forName(clazz.getName(), true, clazz.getClassLoader()); 135 } catch (ClassNotFoundException e) { 136 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); 137 } 138 } 139 140 static { 141 // pre-load and initialize InterruptedException and Cleaner classes 142 // so that we don't get into trouble later in the run loop if there's 143 // memory shortage while loading/initializing them lazily. 144 ensureClassInitialized(InterruptedException.class); 145 ensureClassInitialized(Cleaner.class); 146 } 147 148 ReferenceHandler(ThreadGroup g, String name) { 149 super(g, name); 150 } 151 152 public void run() { 153 while (true) { 154 tryHandlePending(true); 155 } 156 } 157 } 158 159 /** 160 * Try handle pending {@link Reference} if there is one.<p> 161 * Return {@code true} as a hint that there might be another 162 * {@link Reference} pending or {@code false} when there are no more pending 163 * {@link Reference}s at the moment and the program can do some other 164 * useful work instead of looping. 165 * 166 * @param waitForNotify if {@code true} and there was no pending 167 * {@link Reference}, wait until notified from VM 168 * or interrupted; if {@code false}, return immediately 169 * when there is no pending {@link Reference}. 170 * @return {@code true} if there was a {@link Reference} pending and it 171 * was processed, or we waited for notification and either got it 172 * or thread was interrupted before being notified; 173 * {@code false} otherwise. 174 */ 175 static boolean tryHandlePending(boolean waitForNotify) { 176 Reference<Object> r; 177 Cleaner c; 178 try { 179 synchronized (lock) { 180 if (pending != null) { 181 r = pending; 182 // 'instanceof' might throw OutOfMemoryError sometimes 183 // so do this before un-linking 'r' from the 'pending' chain... 184 c = r instanceof Cleaner ? (Cleaner) r : null; 185 // unlink 'r' from 'pending' chain 186 pending = r.discovered; 187 r.discovered = null; 188 } else { 189 // The waiting on the lock may cause an OutOfMemoryError 190 // because it may try to allocate exception objects. 191 if (waitForNotify) { 192 lock.wait(); 193 } 194 // retry if waited 195 return waitForNotify; 196 } 197 } 198 } catch (OutOfMemoryError x) { 199 // Give other threads CPU time so they hopefully drop some live references 200 // and GC reclaims some space. 201 // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above 202 // persistently throws OOME for some time... 203 Thread.yield(); 204 // retry 205 return true; 206 } catch (InterruptedException x) { 207 // retry 208 return true; 209 } 210 211 // Fast path for cleaners 212 if (c != null) { 213 c.clean(); 214 return true; 215 } 216 217 ReferenceQueue<? super Object> q = r.queue; 218 if (q != ReferenceQueue.NULL) q.enqueue(r); 219 return true; 220 } 221 222 static { 223 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 224 for (ThreadGroup tgn = tg; 225 tgn != null; 226 tg = tgn, tgn = tg.getParent()); 227 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 228 /* If there were a special system-only priority greater than 229 * MAX_PRIORITY, it would be used here 230 */ 231 handler.setPriority(Thread.MAX_PRIORITY); 232 handler.setDaemon(true); 233 handler.start(); 234 235 // provide access in SharedSecrets 236 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 237 @Override 238 public boolean tryHandlePendingReference() { 239 return tryHandlePending(false); 240 } 241 }); 242 } 243 244 /* -- Referent accessor and setters -- */ 245 246 /** 247 * Returns this reference object's referent. If this reference object has 248 * been cleared, either by the program or by the garbage collector, then 249 * this method returns <code>null</code>. 250 * 251 * @return The object to which this reference refers, or 252 * <code>null</code> if this reference object has been cleared 253 */ 254 public T get() { 255 return this.referent; 256 } 257 258 /** 259 * Clears this reference object. Invoking this method will not cause this 260 * object to be enqueued. 261 * 262 * <p> This method is invoked only by Java code; when the garbage collector 263 * clears references it does so directly, without invoking this method. 264 */ 265 public void clear() { 266 this.referent = null; 267 } 268 269 270 /* -- Queue operations -- */ 271 272 /** 273 * Tells whether or not this reference object has been enqueued, either by 274 * the program or by the garbage collector. If this reference object was 275 * not registered with a queue when it was created, then this method will 276 * always return <code>false</code>. 277 * 278 * @return <code>true</code> if and only if this reference object has 279 * been enqueued 280 */ 281 public boolean isEnqueued() { 282 return (this.queue == ReferenceQueue.ENQUEUED); 283 } 284 285 /** 286 * Adds this reference object to the queue with which it is registered, 287 * if any. 288 * 289 * <p> This method is invoked only by Java code; when the garbage collector 290 * enqueues references it does so directly, without invoking this method. 291 * 292 * @return <code>true</code> if this reference object was successfully 293 * enqueued; <code>false</code> if it was already enqueued or if 294 * it was not registered with a queue when it was created 295 */ 296 public boolean enqueue() { 297 return this.queue.enqueue(this); 298 } 299 300 301 /* -- Constructors -- */ 302 303 Reference(T referent) { 304 this(referent, null); 305 } 306 307 Reference(T referent, ReferenceQueue<? super T> queue) { 308 this.referent = referent; 309 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 310 } 311 312 }