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 26 package java.lang.ref; 27 28 import jdk.internal.HotSpotIntrinsicCandidate; 29 import jdk.internal.misc.JavaLangRefAccess; 30 import jdk.internal.misc.SharedSecrets; 31 import jdk.internal.vm.annotation.DontInline; 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 volatile 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 private transient Reference<?> 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 private static class Lock { } 118 private static final 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<?> pending; 127 128 /* Discovery phase counter, guarder by above lock. 129 */ 130 private static int discoveryPhase; 131 132 /* Enqueue phase, guarded by enqueuePhaseLock object. 133 */ 134 private static int enqueuePhase; 135 private static final Object enqueuePhaseLock = new Object(); 136 137 /* High-priority thread to enqueue pending References 138 */ 139 private static class ReferenceHandler extends Thread { 140 141 private static void ensureClassInitialized(Class<?> clazz) { 142 try { 143 Class.forName(clazz.getName(), true, clazz.getClassLoader()); 144 } catch (ClassNotFoundException e) { 145 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); 146 } 147 } 148 149 static { 150 // pre-load and initialize InterruptedException class 151 // so that we don't get into trouble later in the run loop if there's 152 // memory shortage while loading/initializing it lazily. 153 ensureClassInitialized(InterruptedException.class); 154 } 155 156 ReferenceHandler(ThreadGroup g, String name) { 157 super(g, null, name, 0, false); 158 } 159 160 public void run() { 161 int[] discoveryPhase = new int[1]; 162 while (true) { 163 Reference<?> p = getPendingReferences(discoveryPhase); 164 enqueuePendingReferences(p, discoveryPhase[0]); 165 } 166 } 167 } 168 169 /** 170 * Blocks until GC discovers some pending references, sets the 0-th element 171 * of given {@code discoveryPhaseHolder} to the phase in which they were 172 * discovered and returns the head of the list of discovered references. 173 * 174 * @param discoveryPhaseHolder a 1-element array to hold the returned 175 * discovery phase. 176 * @return the head of a list of pending references linked via 177 * {@link #discovered} field with {@code null} marking the end of list. 178 */ 179 static Reference<?> getPendingReferences(int[] discoveryPhaseHolder) { 180 Reference<?> p; 181 synchronized (lock) { 182 while ((p = pending) == null) { 183 try { 184 lock.wait(); 185 } catch (OutOfMemoryError x) { 186 // The waiting on the lock may cause an OutOfMemoryError 187 // because it may try to allocate InterruptedException object. 188 // Give other threads CPU time so they hopefully drop some live 189 // references and GC reclaims some space. 190 Thread.yield(); 191 } catch (InterruptedException x) { 192 // ignore interrupts 193 } 194 } 195 pending = null; 196 // increment discoveryPhase counter and return it in a holder array 197 discoveryPhaseHolder[0] = ++discoveryPhase; 198 } 199 return p; 200 } 201 202 /** 203 * @return current finished discovery phase. 204 */ 205 static int getDiscoveryPhase() { 206 synchronized (lock) { 207 return (pending == null) 208 ? discoveryPhase // already incremented 209 : discoveryPhase + 1; // not yet incremented 210 } 211 } 212 213 /** 214 * Enqueue a list of pending {@link Reference}s linked via {@link #discovered} 215 * field with {@code null} marking the end of list. 216 * <p> 217 * The {@link #enqueuePhase} is set to given {@code discoveryPhase} 218 * after all references from the list have been enqueued and any waiters on 219 * {@link #enqueuePhaseLock} are notified. 220 * 221 * @param p a list of pending references linked via {@link #discovered} 222 * field with {@code null} marking the end of list. 223 * @param discoveryPhase the phase in which given references were discovered. 224 */ 225 static void enqueuePendingReferences(Reference<?> p, int discoveryPhase) { 226 try { 227 // distribute unhooked pending references to their respective queues 228 while (p != null) { 229 Reference<?> r = p; 230 p = r.discovered; 231 r.discovered = null; 232 @SuppressWarnings("unchecked") 233 ReferenceQueue<Object> q = (ReferenceQueue) r.queue; 234 if (q != ReferenceQueue.NULL) q.enqueue(r); 235 } 236 } finally { 237 // mark the enqueueing of references discovered in given 238 // discovery phase is finished and notify waiters. 239 synchronized (enqueuePhaseLock) { 240 enqueuePhase = discoveryPhase; 241 enqueuePhaseLock.notifyAll(); 242 } 243 } 244 } 245 246 /** 247 * Triggers discovery of new Reference(s) and returns the phase sequence number 248 * in which they were discovered or previous phase sequence number if no new 249 * Reference(s) were discovered. 250 */ 251 static int discoverReferences() { 252 // trigger discovery of new Reference(s) 253 System.gc(); 254 // obtain the phase in which they were discovered (if any) 255 return getDiscoveryPhase(); 256 } 257 258 /** 259 * Blocks until all Reference(s) that were discovered in given 260 * {@code discoveryPhase} (as returned by {@link #discoverReferences()}) 261 * have been enqueued. 262 * 263 * @param discoveryPhase the discovery phase sequence number. 264 * @throws InterruptedException if interrupted while waiting. 265 */ 266 static void awaitReferencesEnqueued(int discoveryPhase) throws InterruptedException { 267 // await for them to be enqueued 268 synchronized (enqueuePhaseLock) { 269 while (enqueuePhase - discoveryPhase < 0) { 270 enqueuePhaseLock.wait(); 271 } 272 } 273 } 274 275 static { 276 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 277 for (ThreadGroup tgn = tg; 278 tgn != null; 279 tg = tgn, tgn = tg.getParent()); 280 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 281 /* If there were a special system-only priority greater than 282 * MAX_PRIORITY, it would be used here 283 */ 284 handler.setPriority(Thread.MAX_PRIORITY); 285 handler.setDaemon(true); 286 handler.start(); 287 288 // provide access in SharedSecrets 289 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 290 @Override 291 public int discoverReferences() { 292 return Reference.discoverReferences(); 293 } 294 295 @Override 296 public void awaitReferencesEnqueued( 297 int discoveryPhase) throws InterruptedException { 298 Reference.awaitReferencesEnqueued(discoveryPhase); 299 } 300 }); 301 } 302 303 /* -- Referent accessor and setters -- */ 304 305 /** 306 * Returns this reference object's referent. If this reference object has 307 * been cleared, either by the program or by the garbage collector, then 308 * this method returns <code>null</code>. 309 * 310 * @return The object to which this reference refers, or 311 * <code>null</code> if this reference object has been cleared 312 */ 313 @HotSpotIntrinsicCandidate 314 public T get() { 315 return this.referent; 316 } 317 318 /** 319 * Clears this reference object. Invoking this method will not cause this 320 * object to be enqueued. 321 * 322 * <p> This method is invoked only by Java code; when the garbage collector 323 * clears references it does so directly, without invoking this method. 324 */ 325 public void clear() { 326 this.referent = null; 327 } 328 329 330 /* -- Queue operations -- */ 331 332 /** 333 * Tells whether or not this reference object has been enqueued, either by 334 * the program or by the garbage collector. If this reference object was 335 * not registered with a queue when it was created, then this method will 336 * always return <code>false</code>. 337 * 338 * @return <code>true</code> if and only if this reference object has 339 * been enqueued 340 */ 341 public boolean isEnqueued() { 342 return (this.queue == ReferenceQueue.ENQUEUED); 343 } 344 345 /** 346 * Adds this reference object to the queue with which it is registered, 347 * if any. 348 * 349 * <p> This method is invoked only by Java code; when the garbage collector 350 * enqueues references it does so directly, without invoking this method. 351 * 352 * @return <code>true</code> if this reference object was successfully 353 * enqueued; <code>false</code> if it was already enqueued or if 354 * it was not registered with a queue when it was created 355 */ 356 public boolean enqueue() { 357 return this.queue.enqueue(this); 358 } 359 360 361 /* -- Constructors -- */ 362 363 Reference(T referent) { 364 this(referent, null); 365 } 366 367 Reference(T referent, ReferenceQueue<? super T> queue) { 368 this.referent = referent; 369 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 370 } 371 372 /** 373 * Ensures that the object referenced by the given reference remains 374 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 375 * regardless of any prior actions of the program that might otherwise cause 376 * the object to become unreachable; thus, the referenced object is not 377 * reclaimable by garbage collection at least until after the invocation of 378 * this method. Invocation of this method does not itself initiate garbage 379 * collection or finalization. 380 * 381 * <p> This method establishes an ordering for 382 * <a href="package-summary.html#reachability"><em>strong reachability</em></a> 383 * with respect to garbage collection. It controls relations that are 384 * otherwise only implicit in a program -- the reachability conditions 385 * triggering garbage collection. This method is designed for use in 386 * uncommon situations of premature finalization where using 387 * {@code synchronized} blocks or methods, or using other synchronization 388 * facilities are not possible or do not provide the desired control. This 389 * method is applicable only when reclamation may have visible effects, 390 * which is possible for objects with finalizers (See 391 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6"> 392 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>) 393 * that are implemented in ways that rely on ordering control for correctness. 394 * 395 * @apiNote 396 * Finalization may occur whenever the virtual machine detects that no 397 * reference to an object will ever be stored in the heap: The garbage 398 * collector may reclaim an object even if the fields of that object are 399 * still in use, so long as the object has otherwise become unreachable. 400 * This may have surprising and undesirable effects in cases such as the 401 * following example in which the bookkeeping associated with a class is 402 * managed through array indices. Here, method {@code action} uses a 403 * {@code reachabilityFence} to ensure that the {@code Resource} object is 404 * not reclaimed before bookkeeping on an associated 405 * {@code ExternalResource} has been performed; in particular here, to 406 * ensure that the array slot holding the {@code ExternalResource} is not 407 * nulled out in method {@link Object#finalize}, which may otherwise run 408 * concurrently. 409 * 410 * <pre> {@code 411 * class Resource { 412 * private static ExternalResource[] externalResourceArray = ... 413 * 414 * int myIndex; 415 * Resource(...) { 416 * myIndex = ... 417 * externalResourceArray[myIndex] = ...; 418 * ... 419 * } 420 * protected void finalize() { 421 * externalResourceArray[myIndex] = null; 422 * ... 423 * } 424 * public void action() { 425 * try { 426 * // ... 427 * int i = myIndex; 428 * Resource.update(externalResourceArray[i]); 429 * } finally { 430 * Reference.reachabilityFence(this); 431 * } 432 * } 433 * private static void update(ExternalResource ext) { 434 * ext.status = ...; 435 * } 436 * }}</pre> 437 * 438 * Here, the invocation of {@code reachabilityFence} is nonintuitively 439 * placed <em>after</em> the call to {@code update}, to ensure that the 440 * array slot is not nulled out by {@link Object#finalize} before the 441 * update, even if the call to {@code action} was the last use of this 442 * object. This might be the case if, for example a usage in a user program 443 * had the form {@code new Resource().action();} which retains no other 444 * reference to this {@code Resource}. While probably overkill here, 445 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 446 * that it is invoked across all paths in the method. In a method with more 447 * complex control paths, you might need further precautions to ensure that 448 * {@code reachabilityFence} is encountered along all of them. 449 * 450 * <p> It is sometimes possible to better encapsulate use of 451 * {@code reachabilityFence}. Continuing the above example, if it were 452 * acceptable for the call to method {@code update} to proceed even if the 453 * finalizer had already executed (nulling out slot), then you could 454 * localize use of {@code reachabilityFence}: 455 * 456 * <pre> {@code 457 * public void action2() { 458 * // ... 459 * Resource.update(getExternalResource()); 460 * } 461 * private ExternalResource getExternalResource() { 462 * ExternalResource ext = externalResourceArray[myIndex]; 463 * Reference.reachabilityFence(this); 464 * return ext; 465 * }}</pre> 466 * 467 * <p> Method {@code reachabilityFence} is not required in constructions 468 * that themselves ensure reachability. For example, because objects that 469 * are locked cannot, in general, be reclaimed, it would suffice if all 470 * accesses of the object, in all methods of class {@code Resource} 471 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 472 * blocks. (Further, such blocks must not include infinite loops, or 473 * themselves be unreachable, which fall into the corner case exceptions to 474 * the "in general" disclaimer.) However, method {@code reachabilityFence} 475 * remains a better option in cases where this approach is not as efficient, 476 * desirable, or possible; for example because it would encounter deadlock. 477 * 478 * @param ref the reference. If {@code null}, this method has no effect. 479 * @since 9 480 */ 481 @DontInline 482 public static void reachabilityFence(Object ref) { 483 // Does nothing, because this method is annotated with @DontInline 484 // HotSpot needs to retain the ref and not GC it before a call to this 485 // method 486 } 487 488 }