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 Reference<?> next; 103 104 /* When active: next element in a discovered reference list maintained by GC (or this if last) 105 * pending: next element in the pending list (or null if last) 106 * otherwise: NULL 107 */ 108 transient private Reference<?> discovered; /* used by VM */ 109 110 111 /* Object used to synchronize with the garbage collector. The collector 112 * must acquire this lock at the beginning of each collection cycle. It is 113 * therefore critical that any code holding this lock complete as quickly 114 * as possible, allocate no new objects, and avoid calling user code. 115 */ 116 static private class Lock { } 117 private static final Lock lock = new Lock(); 118 119 120 /* List of References waiting to be enqueued. The collector adds 121 * References to this list, while the Reference-handler thread removes 122 * them. This list is protected by the above lock object. The 123 * list uses the discovered field to link its elements. 124 */ 125 private static Reference<Object> pending = null; 126 127 /* Max. number of Reference(s) to unhook from pending chain in one chunk 128 * before releasing the lock, handling them and grabbing the 129 * lock again. 130 */ 131 private static final int UNHOOK_CHUNK_SIZE = 32768; 132 133 /* Max. number of Finalizer(s) to execute in one ForkJoinTask 134 */ 135 private static final int FINALIZE_CHUNK_SIZE = 256; 136 137 /* Max. number of Reference(s) to enqueue in one chunk 138 */ 139 private static final int ENQUEUE_CHUNK_SIZE = 256; 140 141 private static class ReferenceHandler extends ManagedLocalsThread { 142 143 private static void ensureClassInitialized(Class<?> clazz) { 144 try { 145 Class.forName(clazz.getName(), true, clazz.getClassLoader()); 146 } catch (ClassNotFoundException e) { 147 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); 148 } 149 } 150 151 static { 152 // pre-load and initialize InterruptedException and Cleaner classes 153 // so that we don't get into trouble later in the run loop if there's 154 // memory shortage while loading/initializing them lazily. 155 ensureClassInitialized(InterruptedException.class); 156 ensureClassInitialized(Cleaner.class); 157 } 158 159 ReferenceHandler(ThreadGroup g, String name) { 160 super(g, name); 161 } 162 163 public void run() { 164 // wait for VM to boot-up before starting reference handling 165 // ForkJoinPool since it needs access to some system properties 166 // and Finalizer needs access to SharedSecrets. 167 while (true) { 168 try { 169 sun.misc.VM.awaitBooted(); 170 break; 171 } catch (InterruptedException e) { 172 // ignore; 173 } 174 } 175 // start reference handling ForkJoinPool 176 ReferenceHandling.start(); 177 // enter endless loop 178 boolean[] morePending = new boolean[1]; 179 while (true) { 180 Reference<?> chunk = null; 181 try { 182 synchronized (lock) { 183 chunk = Reference.unhookPendingChunk(UNHOOK_CHUNK_SIZE, morePending); 184 if (chunk == null) { 185 // waiting on notification can throw InterruptedException 186 // if the thread is interrupted, but also OutOfMemoryError 187 // if the InterruptedException can not be allocated. 188 lock.wait(); 189 // since we have already re-obtained the lock, we can 190 // re-try poll and will typically get a non-null chunk. 191 chunk = Reference.unhookPendingChunk(UNHOOK_CHUNK_SIZE, morePending); 192 } 193 } 194 } catch (OutOfMemoryError e) { 195 // give other threads some time so they hopefully release some 196 // references and GC reclaims some space, then retry... 197 Thread.yield(); 198 } catch (InterruptedException e) { 199 // ignore 200 } 201 if (chunk != null) { 202 if (morePending[0]) { 203 // submit a handling task and return for next chunk 204 new ReferenceHandling.PendingChunkHandler(chunk).submit(); 205 } else { 206 // no more pending, so we can handle the chunk directly 207 Reference.handlePendingChunk(chunk); 208 } 209 } 210 } 211 } 212 } 213 214 /** 215 * Try handle a chunk of pending {@link Reference}s if there are any.<p> 216 * Return {@code true} as a hint that there are more 217 * {@link Reference}s pending or {@code false} when there are no more pending 218 * {@link Reference}s at the moment and the program can do some other 219 * useful work instead of looping. 220 * 221 * @return {@code true} if there is be more {@link Reference}s pending. 222 */ 223 static boolean tryHandlePending() { 224 Reference<?> r; 225 synchronized (lock) { 226 r = unhookPendingChunk(UNHOOK_CHUNK_SIZE, null); 227 } 228 if (r == null) return false; 229 handlePendingChunk(r); 230 synchronized (lock) { 231 return pending != null; 232 } 233 } 234 235 /** 236 * Unhooks a chunk of max. {@code chunkSize} references from pending chain and 237 * returns the head of the chunk; elements of the chunk can be reached using 238 * {@link #next} links; the last in chunk is linked to itself. 239 * 240 * @param chunkSize max. number of references to unhook from the pending chain 241 * @param morePending if non null, it should be a boolean array with length 1 242 * to hold the additional result - a flag indicating that 243 * there are more pending references waiting after a chunk 244 * of them has been returned. 245 * @return the head of the chunk of max. {@code chunkSize} pending references or 246 * null if there are none pending. 247 */ 248 private static Reference<?> unhookPendingChunk(int chunkSize, boolean[] morePending) { 249 // assert Thread.holdsLock(lock); 250 Reference<?> r; 251 if ((r = pending) != null) { 252 // pending state invariant established by VM: 253 // assert r.next == r; 254 // move a chunk of pending/discovered references to a 255 // temporary local r/next chain 256 Reference<?> rd = r.discovered; 257 for (int i = 0; rd != null; rd = r.discovered) { 258 r.discovered = null; 259 if (++i >= chunkSize) { 260 break; 261 } 262 rd.next = r; 263 r = rd; 264 } 265 pending = (Reference) rd; 266 if (morePending != null) morePending[0] = (rd != null); 267 } else { 268 if (morePending != null) morePending[0] = false; 269 } 270 return r; 271 } 272 273 /** 274 * Handles a non-null chunk of pending references 275 * (obtained using {@link #unhookPendingChunk}) and handles 276 * them as following: 277 * <ul> 278 * <li>Cleaner(s) are executed immediately</li> 279 * <li>Finalizer(s) are submitted as ForkJoinTask(s)</li> 280 * <li>all other Reference(s) are enqueued in their respected queues</li> 281 * </ul> 282 * @param chunk the head of a chunk of pending references 283 */ 284 static void handlePendingChunk(Reference<?> chunk) { 285 // batch finalizers into chunks 286 Reference<?> finalizers = null; 287 int finalizersCount = 0; 288 // batch consecutive references with same queue into chunks 289 Reference<?> referencesHead = null, referencesTail = null; 290 int referencesCount = 0; 291 ReferenceQueue<?> referenceQueue = null; 292 // dispatch references to appropriate targets 293 for (Reference<?> r = chunk, rn = r.next; ; r = rn, rn = r.next) { 294 if (r instanceof Cleaner) { // Fast path for cleaners 295 // take 'r' off the chain 296 r.next = r; 297 ((Cleaner) r).clean(); 298 } else if (r instanceof Finalizer) { // Submit task(s) for finalizers 299 // hook onto the finalizers chain 300 r.next = (finalizers == null) ? r : finalizers; 301 finalizers = r; 302 if (++finalizersCount >= FINALIZE_CHUNK_SIZE) { 303 // when chunk of finalizers is full, submit a task 304 new ReferenceHandling.FinalizerHandler(finalizers).submit(); 305 finalizers = null; 306 finalizersCount = 0; 307 } 308 } else { // Enqueue all other references 309 // take 'r' off the chain 310 r.next = r; 311 ReferenceQueue<?> q = r.queue; 312 if (q != ReferenceQueue.NULL && q.markEnqueued(r)) { // markEnqueued is atomic 313 if (referenceQueue == null || referenceQueue == q) { 314 // no queue or same queue -> hook onto the references[Head|Tail] chain 315 if (referencesHead == null) { 316 // assert referencesTail == null && referenceQueue == null && 317 // referencesCount == 0 && r.next == r; 318 referenceQueue = q; 319 referencesHead = referencesTail = r; 320 } else { 321 // assert referencesTail != null && referenceQueue == q && 322 // referencesCount > 0; 323 r.next = referencesHead; 324 referencesHead = r; 325 } 326 if (++referencesCount >= ENQUEUE_CHUNK_SIZE) { 327 // when a chunk of references is full, add them to queue 328 referenceQueue.addChunk(referencesHead, referencesTail); 329 referencesHead = referencesTail = null; 330 referenceQueue = null; 331 referencesCount = 0; 332 } 333 } else { 334 // when a different queue is encountered, 335 // add collected chunk to it's queue and start collecting 336 // into new queue... 337 // assert referenceQueue != null && referenceQueue != q && 338 // referencesHead != null && referencesTail != null && 339 // referencesCount > 0 && r.next == r; 340 referenceQueue.addChunk(referencesHead, referencesTail); 341 referenceQueue = q; 342 referencesHead = referencesTail = r; 343 referencesCount = 1; 344 } 345 } 346 } 347 if (rn == r) { // last in chain 348 break; 349 } 350 } 351 // any finalizers left? 352 if (finalizers != null) { 353 new ReferenceHandling.FinalizerHandler(finalizers).submit(); 354 finalizers = null; 355 finalizersCount = 0; 356 } 357 // any references left to enqueue? 358 if (referenceQueue != null) { 359 // assert referencesHead != null && referencesTail != null && referencesCount > 0; 360 referenceQueue.addChunk(referencesHead, referencesTail); 361 referencesHead = referencesTail = null; 362 referenceQueue = null; 363 referencesCount = 0; 364 } 365 } 366 367 /* -- Referent accessor and setters -- */ 368 369 /** 370 * Returns this reference object's referent. If this reference object has 371 * been cleared, either by the program or by the garbage collector, then 372 * this method returns <code>null</code>. 373 * 374 * @return The object to which this reference refers, or 375 * <code>null</code> if this reference object has been cleared 376 */ 377 public T get() { 378 return this.referent; 379 } 380 381 /** 382 * Clears this reference object. Invoking this method will not cause this 383 * object to be enqueued. 384 * 385 * <p> This method is invoked only by Java code; when the garbage collector 386 * clears references it does so directly, without invoking this method. 387 */ 388 public void clear() { 389 this.referent = null; 390 } 391 392 393 /* -- Queue operations -- */ 394 395 /** 396 * Tells whether or not this reference object has been enqueued, either by 397 * the program or by the garbage collector. If this reference object was 398 * not registered with a queue when it was created, then this method will 399 * always return <code>false</code>. 400 * 401 * @return <code>true</code> if and only if this reference object has 402 * been enqueued 403 */ 404 public boolean isEnqueued() { 405 return (this.queue == ReferenceQueue.ENQUEUED); 406 } 407 408 /** 409 * Adds this reference object to the queue with which it is registered, 410 * if any. 411 * 412 * <p> This method is invoked only by Java code; when the garbage collector 413 * enqueues references it does so directly, without invoking this method. 414 * 415 * @return <code>true</code> if this reference object was successfully 416 * enqueued; <code>false</code> if it was already enqueued or if 417 * it was not registered with a queue when it was created 418 */ 419 public boolean enqueue() { 420 return this.queue.enqueue(this); 421 } 422 423 424 /* -- Constructors -- */ 425 426 Reference(T referent) { 427 this(referent, null); 428 } 429 430 Reference(T referent, ReferenceQueue<? super T> queue) { 431 this.referent = referent; 432 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 433 } 434 435 // Unsafe machinery 436 437 @SuppressWarnings("unchecked") 438 T getReferentVolatile() { 439 return (T) UNSAFE.getObjectVolatile(this, referentOffset); 440 } 441 442 boolean casReferent(T cmp, T val) { 443 return UNSAFE.compareAndSwapObject(this, referentOffset, cmp, val); 444 } 445 446 void lazySetQueue(ReferenceQueue<? super T> val) { 447 UNSAFE.putOrderedObject(this, queueOffset, val); 448 } 449 450 boolean casQueue(ReferenceQueue<?> cmp, ReferenceQueue<? super T> val) { 451 return UNSAFE.compareAndSwapObject(this, queueOffset, cmp, val); 452 } 453 454 private static final sun.misc.Unsafe UNSAFE; 455 private static final long referentOffset; 456 private static final long queueOffset; 457 458 static { 459 try { 460 UNSAFE = sun.misc.Unsafe.getUnsafe(); 461 Class<Reference> rc = Reference.class; 462 referentOffset = UNSAFE.objectFieldOffset(rc.getDeclaredField("referent")); 463 queueOffset = UNSAFE.objectFieldOffset(rc.getDeclaredField("queue")); 464 } catch (Exception e) { 465 throw new Error(e); 466 } 467 468 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 469 for (ThreadGroup tgn = tg; 470 tgn != null; 471 tg = tgn, tgn = tg.getParent()); 472 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 473 /* If there were a special system-only priority greater than 474 * MAX_PRIORITY, it would be used here 475 */ 476 handler.setPriority(Thread.MAX_PRIORITY); 477 handler.setDaemon(true); 478 handler.start(); 479 480 // provide access in SharedSecrets 481 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 482 @Override 483 public boolean tryHandlePendingReference() { 484 return tryHandlePending(); 485 } 486 }); 487 } 488 }