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 a Reference is de-queued from ReferenceQueue, Reference.next 98 * points to this object. 99 */ 100 private static class Dequeued extends Reference<Void> { Dequeued() { super(null); } } 101 static final Reference DEQUEUED = new Dequeued(); 102 103 /* When active: NULL 104 * pending: this 105 * Enqueued: next reference in queue (or this if last) 106 * Inactive: DEQUEUED 107 */ 108 @SuppressWarnings("rawtypes") 109 Reference next; 110 111 /* When active: next element in a discovered reference list maintained by GC (or this if last) 112 * pending: next element in the pending list (or null if last) 113 * otherwise: NULL 114 */ 115 transient private Reference<T> discovered; /* used by VM */ 116 117 118 /* Object used to synchronize with the garbage collector. The collector 119 * must acquire this lock at the beginning of each collection cycle. It is 120 * therefore critical that any code holding this lock complete as quickly 121 * as possible, allocate no new objects, and avoid calling user code. 122 */ 123 static private class Lock { } 124 private static Lock lock = new Lock(); 125 126 127 /* List of References waiting to be enqueued. The collector adds 128 * References to this list, while the Reference-handler thread removes 129 * them. This list is protected by the above lock object. The 130 * list uses the discovered field to link its elements. 131 */ 132 private static Reference<Object> pending = null; 133 134 /* High-priority thread to enqueue pending References 135 */ 136 private static class ReferenceHandler extends ManagedLocalsThread { 137 138 private static void ensureClassInitialized(Class<?> clazz) { 139 try { 140 Class.forName(clazz.getName(), true, clazz.getClassLoader()); 141 } catch (ClassNotFoundException e) { 142 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); 143 } 144 } 145 146 static { 147 // pre-load and initialize InterruptedException and Cleaner classes 148 // so that we don't get into trouble later in the run loop if there's 149 // memory shortage while loading/initializing them lazily. 150 ensureClassInitialized(InterruptedException.class); 151 ensureClassInitialized(Cleaner.class); 152 } 153 154 ReferenceHandler(ThreadGroup g, String name) { 155 super(g, name); 156 } 157 158 public void run() { 159 while (true) { 160 tryHandlePending(true); 161 } 162 } 163 } 164 165 /** 166 * Try handle pending {@link Reference} if there is one.<p> 167 * Return {@code true} as a hint that there might be another 168 * {@link Reference} pending or {@code false} when there are no more pending 169 * {@link Reference}s at the moment and the program can do some other 170 * useful work instead of looping. 171 * 172 * @param waitForNotify if {@code true} and there was no pending 173 * {@link Reference}, wait until notified from VM 174 * or interrupted; if {@code false}, return immediately 175 * when there is no pending {@link Reference}. 176 * @return {@code true} if there was a {@link Reference} pending and it 177 * was processed, or we waited for notification and either got it 178 * or thread was interrupted before being notified; 179 * {@code false} otherwise. 180 */ 181 static boolean tryHandlePending(boolean waitForNotify) { 182 Reference<Object> r; 183 Cleaner c; 184 try { 185 synchronized (lock) { 186 if (pending != null) { 187 r = pending; 188 // 'instanceof' might throw OutOfMemoryError sometimes 189 // so do this before un-linking 'r' from the 'pending' chain... 190 c = r instanceof Cleaner ? (Cleaner) r : null; 191 // unlink 'r' from 'pending' chain 192 pending = r.discovered; 193 r.discovered = null; 194 } else { 195 // The waiting on the lock may cause an OutOfMemoryError 196 // because it may try to allocate exception objects. 197 if (waitForNotify) { 198 lock.wait(); 199 } 200 // retry if waited 201 return waitForNotify; 202 } 203 } 204 } catch (OutOfMemoryError x) { 205 // Give other threads CPU time so they hopefully drop some live references 206 // and GC reclaims some space. 207 // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above 208 // persistently throws OOME for some time... 209 Thread.yield(); 210 // retry 211 return true; 212 } catch (InterruptedException x) { 213 // retry 214 return true; 215 } 216 217 // Fast path for cleaners 218 if (c != null) { 219 c.clean(); 220 return true; 221 } 222 223 ReferenceQueue<? super Object> q = r.queue; 224 if (q != ReferenceQueue.NULL) q.enqueue(r); 225 return true; 226 } 227 228 static { 229 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 230 for (ThreadGroup tgn = tg; 231 tgn != null; 232 tg = tgn, tgn = tg.getParent()); 233 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 234 /* If there were a special system-only priority greater than 235 * MAX_PRIORITY, it would be used here 236 */ 237 handler.setPriority(Thread.MAX_PRIORITY); 238 handler.setDaemon(true); 239 handler.start(); 240 241 // provide access in SharedSecrets 242 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 243 @Override 244 public boolean tryHandlePendingReference() { 245 return tryHandlePending(false); 246 } 247 }); 248 } 249 250 /* -- Referent accessor and setters -- */ 251 252 /** 253 * Returns this reference object's referent. If this reference object has 254 * been cleared, either by the program or by the garbage collector, then 255 * this method returns <code>null</code>. 256 * 257 * @return The object to which this reference refers, or 258 * <code>null</code> if this reference object has been cleared 259 */ 260 public T get() { 261 return this.referent; 262 } 263 264 /** 265 * Clears this reference object. Invoking this method will not cause this 266 * object to be enqueued. 267 * 268 * <p> This method is invoked only by Java code; when the garbage collector 269 * clears references it does so directly, without invoking this method. 270 */ 271 public void clear() { 272 this.referent = null; 273 } 274 275 276 /* -- Queue operations -- */ 277 278 /** 279 * Tells whether or not this reference object has been enqueued, either by 280 * the program or by the garbage collector. If this reference object was 281 * not registered with a queue when it was created, then this method will 282 * always return <code>false</code>. 283 * 284 * @return <code>true</code> if and only if this reference object has 285 * been enqueued 286 */ 287 public boolean isEnqueued() { 288 return (this.queue == ReferenceQueue.ENQUEUED); 289 } 290 291 /** 292 * Adds this reference object to the queue with which it is registered, 293 * if any. 294 * 295 * <p> This method is invoked only by Java code; when the garbage collector 296 * enqueues references it does so directly, without invoking this method. 297 * 298 * @return <code>true</code> if this reference object was successfully 299 * enqueued; <code>false</code> if it was already enqueued or if 300 * it was not registered with a queue when it was created 301 */ 302 public boolean enqueue() { 303 return this.queue.enqueue(this); 304 } 305 306 307 /* -- Constructors -- */ 308 309 Reference(T referent) { 310 this(referent, null); 311 } 312 313 Reference(T referent, ReferenceQueue<? super T> queue) { 314 this.referent = referent; 315 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 316 } 317 318 }