1 /* 2 * Copyright (c) 1997, 2018, 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.vm.annotation.ForceInline; 29 import jdk.internal.HotSpotIntrinsicCandidate; 30 import jdk.internal.access.JavaLangRefAccess; 31 import jdk.internal.access.SharedSecrets; 32 import jdk.internal.ref.Cleaner; 33 34 /** 35 * Abstract base class for reference objects. This class defines the 36 * operations common to all reference objects. Because reference objects are 37 * implemented in close cooperation with the garbage collector, this class may 38 * not be subclassed directly. 39 * 40 * @author Mark Reinhold 41 * @since 1.2 42 */ 43 44 public abstract class Reference<T> { 45 46 /* The state of a Reference object is characterized by two attributes. It 47 * may be either "active", "pending", or "inactive". It may also be 48 * either "registered", "enqueued", "dequeued", or "unregistered". 49 * 50 * Active: Subject to special treatment by the garbage collector. Some 51 * time after the collector detects that the reachability of the 52 * referent has changed to the appropriate state, the collector 53 * "notifies" the reference, changing the state to either "pending" or 54 * "inactive". 55 * referent != null; discovered = null, or in GC discovered list. 56 * 57 * Pending: An element of the pending-Reference list, waiting to be 58 * processed by the ReferenceHandler thread. The pending-Reference 59 * list is linked through the discovered fields of references in the 60 * list. 61 * referent = null; discovered = next element in pending-Reference list. 62 * 63 * Inactive: Neither Active nor Pending. 64 * referent = null. 65 * 66 * Registered: Associated with a queue when created, and not yet added 67 * to the queue. 68 * queue = the associated queue. 69 * 70 * Enqueued: Added to the associated queue, and not yet removed. 71 * queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to 72 * indicate end of list. 73 * 74 * Dequeued: Added to the associated queue and then removed. 75 * queue = ReferenceQueue.NULL; next = this. 76 * 77 * Unregistered: Not associated with a queue when created. 78 * queue = ReferenceQueue.NULL. 79 * 80 * The collector only needs to examine the referent field and the 81 * discovered field to determine whether a (non-FinalReference) Reference 82 * object needs special treatment. If the referent is non-null and not 83 * known to be live, then it may need to be discovered for possible later 84 * notification. But if the discovered field is non-null, then it has 85 * already been discovered. 86 * 87 * FinalReference (which exists to support finalization) differs from 88 * other references, because a FinalReference is not cleared when 89 * notified. The referent being null or not cannot be used to distinguish 90 * between the active state and pending or inactive states. However, 91 * FinalReferences do not support enqueue(). Instead, the next field of a 92 * FinalReference object is set to "this" when it is added to the 93 * pending-Reference list. The use of "this" as the value of next in the 94 * enqueued and dequeued states maintains the non-active state. An 95 * additional check that the next field is null is required to determine 96 * that a FinalReference object is active. 97 * 98 * Initial states: 99 * [active/registered] 100 * [active/unregistered] [1] 101 * 102 * Transitions: 103 * clear 104 * [active/registered] -------> [inactive/registered] 105 * | | 106 * | | enqueue [2] 107 * | GC enqueue [2] | 108 * | -----------------| 109 * | | 110 * v | 111 * [pending/registered] --- v 112 * | | ReferenceHandler 113 * | enqueue [2] |---> [inactive/enqueued] 114 * v | | 115 * [pending/enqueued] --- | 116 * | | poll/remove 117 * | poll/remove | 118 * | | 119 * v ReferenceHandler v 120 * [pending/dequeued] ------> [inactive/dequeued] 121 * 122 * 123 * clear/enqueue/GC [3] 124 * [active/unregistered] ------ 125 * | | 126 * | GC | 127 * | |--> [inactive/unregistered] 128 * v | 129 * [pending/unregistered] ------ 130 * ReferenceHandler 131 * 132 * Terminal states: 133 * [inactive/dequeued] 134 * [inactive/unregistered] 135 * 136 * Unreachable states (because enqueue also clears): 137 * [active/enqeued] 138 * [active/dequeued] 139 * 140 * [1] Unregistered is not permitted for FinalReferences. 141 * 142 * [2] These transitions are not possible for FinalReferences, making 143 * [pending/enqueued] and [pending/dequeued] unreachable, and 144 * [inactive/registered] terminal. 145 * 146 * [3] The garbage collector may directly transition a Reference 147 * from [active/unregistered] to [inactive/unregistered], 148 * bypassing the pending-Reference list. 149 */ 150 151 private T referent; /* Treated specially by GC */ 152 153 /* The queue this reference gets enqueued to by GC notification or by 154 * calling enqueue(). 155 * 156 * When registered: the queue with which this reference is registered. 157 * enqueued: ReferenceQueue.ENQUEUE 158 * dequeued: ReferenceQueue.NULL 159 * unregistered: ReferenceQueue.NULL 160 */ 161 volatile ReferenceQueue<? super T> queue; 162 163 /* The link in a ReferenceQueue's list of Reference objects. 164 * 165 * When registered: null 166 * enqueued: next element in queue (or this if last) 167 * dequeued: this (marking FinalReferences as inactive) 168 * unregistered: null 169 */ 170 @SuppressWarnings("rawtypes") 171 volatile Reference next; 172 173 /* Used by the garbage collector to accumulate Reference objects that need 174 * to be revisited in order to decide whether they should be notified. 175 * Also used as the link in the pending-Reference list. The discovered 176 * field and the next field are distinct to allow the enqueue() method to 177 * be applied to a Reference object while it is either in the 178 * pending-Reference list or in the garbage collector's discovered set. 179 * 180 * When active: null or next element in a discovered reference list 181 * maintained by the GC (or this if last) 182 * pending: next element in the pending-Reference list (null if last) 183 * inactive: null 184 */ 185 private transient Reference<T> discovered; 186 187 188 /* High-priority thread to enqueue pending References 189 */ 190 private static class ReferenceHandler extends Thread { 191 192 private static void ensureClassInitialized(Class<?> clazz) { 193 try { 194 Class.forName(clazz.getName(), true, clazz.getClassLoader()); 195 } catch (ClassNotFoundException e) { 196 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); 197 } 198 } 199 200 static { 201 // pre-load and initialize Cleaner class so that we don't 202 // get into trouble later in the run loop if there's 203 // memory shortage while loading/initializing it lazily. 204 ensureClassInitialized(Cleaner.class); 205 } 206 207 ReferenceHandler(ThreadGroup g, String name) { 208 super(g, null, name, 0, false); 209 } 210 211 public void run() { 212 while (true) { 213 processPendingReferences(); 214 } 215 } 216 } 217 218 /* 219 * Atomically get and clear (set to null) the VM's pending-Reference list. 220 */ 221 private static native Reference<Object> getAndClearReferencePendingList(); 222 223 /* 224 * Test whether the VM's pending-Reference list contains any entries. 225 */ 226 private static native boolean hasReferencePendingList(); 227 228 /* 229 * Wait until the VM's pending-Reference list may be non-null. 230 */ 231 private static native void waitForReferencePendingList(); 232 233 private static final Object processPendingLock = new Object(); 234 private static boolean processPendingActive = false; 235 236 private static void processPendingReferences() { 237 // Only the singleton reference processing thread calls 238 // waitForReferencePendingList() and getAndClearReferencePendingList(). 239 // These are separate operations to avoid a race with other threads 240 // that are calling waitForReferenceProcessing(). 241 waitForReferencePendingList(); 242 Reference<Object> pendingList; 243 synchronized (processPendingLock) { 244 pendingList = getAndClearReferencePendingList(); 245 processPendingActive = true; 246 } 247 while (pendingList != null) { 248 Reference<Object> ref = pendingList; 249 pendingList = ref.discovered; 250 ref.discovered = null; 251 252 if (ref instanceof Cleaner) { 253 ((Cleaner)ref).clean(); 254 // Notify any waiters that progress has been made. 255 // This improves latency for nio.Bits waiters, which 256 // are the only important ones. 257 synchronized (processPendingLock) { 258 processPendingLock.notifyAll(); 259 } 260 } else { 261 ReferenceQueue<? super Object> q = ref.queue; 262 if (q != ReferenceQueue.NULL) q.enqueue(ref); 263 } 264 } 265 // Notify any waiters of completion of current round. 266 synchronized (processPendingLock) { 267 processPendingActive = false; 268 processPendingLock.notifyAll(); 269 } 270 } 271 272 // Wait for progress in reference processing. 273 // 274 // Returns true after waiting (for notification from the reference 275 // processing thread) if either (1) the VM has any pending 276 // references, or (2) the reference processing thread is 277 // processing references. Otherwise, returns false immediately. 278 private static boolean waitForReferenceProcessing() 279 throws InterruptedException 280 { 281 synchronized (processPendingLock) { 282 if (processPendingActive || hasReferencePendingList()) { 283 // Wait for progress, not necessarily completion. 284 processPendingLock.wait(); 285 return true; 286 } else { 287 return false; 288 } 289 } 290 } 291 292 static { 293 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 294 for (ThreadGroup tgn = tg; 295 tgn != null; 296 tg = tgn, tgn = tg.getParent()); 297 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 298 /* If there were a special system-only priority greater than 299 * MAX_PRIORITY, it would be used here 300 */ 301 handler.setPriority(Thread.MAX_PRIORITY); 302 handler.setDaemon(true); 303 handler.start(); 304 305 // provide access in SharedSecrets 306 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 307 @Override 308 public boolean waitForReferenceProcessing() 309 throws InterruptedException 310 { 311 return Reference.waitForReferenceProcessing(); 312 } 313 314 @Override 315 public void runFinalization() { 316 Finalizer.runFinalization(); 317 } 318 }); 319 } 320 321 /* -- Referent accessor and setters -- */ 322 323 /** 324 * Returns this reference object's referent. If this reference object has 325 * been cleared, either by the program or by the garbage collector, then 326 * this method returns <code>null</code>. 327 * 328 * @return The object to which this reference refers, or 329 * <code>null</code> if this reference object has been cleared 330 */ 331 @HotSpotIntrinsicCandidate 332 public T get() { 333 return this.referent; 334 } 335 336 /** 337 * Clears this reference object. Invoking this method will not cause this 338 * object to be enqueued. 339 * 340 * <p> This method is invoked only by Java code; when the garbage collector 341 * clears references it does so directly, without invoking this method. 342 */ 343 public void clear() { 344 this.referent = null; 345 } 346 347 /* -- Queue operations -- */ 348 349 /** 350 * Tells whether or not this reference object has been enqueued, either by 351 * the program or by the garbage collector. If this reference object was 352 * not registered with a queue when it was created, then this method will 353 * always return <code>false</code>. 354 * 355 * @return <code>true</code> if and only if this reference object has 356 * been enqueued 357 */ 358 public boolean isEnqueued() { 359 return (this.queue == ReferenceQueue.ENQUEUED); 360 } 361 362 /** 363 * Clears this reference object and adds it to the queue with which 364 * it is registered, if any. 365 * 366 * <p> This method is invoked only by Java code; when the garbage collector 367 * enqueues references it does so directly, without invoking this method. 368 * 369 * @return <code>true</code> if this reference object was successfully 370 * enqueued; <code>false</code> if it was already enqueued or if 371 * it was not registered with a queue when it was created 372 */ 373 public boolean enqueue() { 374 this.referent = null; 375 return this.queue.enqueue(this); 376 } 377 378 /** 379 * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be 380 * meaningfully cloned. Construct a new {@code Reference} instead. 381 * 382 * @return never returns normally 383 * @throws CloneNotSupportedException always 384 * 385 * @since 11 386 */ 387 @Override 388 protected Object clone() throws CloneNotSupportedException { 389 throw new CloneNotSupportedException(); 390 } 391 392 /* -- Constructors -- */ 393 394 Reference(T referent) { 395 this(referent, null); 396 } 397 398 Reference(T referent, ReferenceQueue<? super T> queue) { 399 if (referent != null && referent.getClass().isInlineClass()) { 400 throw new IllegalArgumentException("cannot reference an inline value of type: " + 401 referent.getClass().getName()); 402 } 403 this.referent = referent; 404 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 405 } 406 407 /** 408 * Ensures that the object referenced by the given reference remains 409 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 410 * regardless of any prior actions of the program that might otherwise cause 411 * the object to become unreachable; thus, the referenced object is not 412 * reclaimable by garbage collection at least until after the invocation of 413 * this method. Invocation of this method does not itself initiate garbage 414 * collection or finalization. 415 * 416 * <p> This method establishes an ordering for 417 * <a href="package-summary.html#reachability"><em>strong reachability</em></a> 418 * with respect to garbage collection. It controls relations that are 419 * otherwise only implicit in a program -- the reachability conditions 420 * triggering garbage collection. This method is designed for use in 421 * uncommon situations of premature finalization where using 422 * {@code synchronized} blocks or methods, or using other synchronization 423 * facilities are not possible or do not provide the desired control. This 424 * method is applicable only when reclamation may have visible effects, 425 * which is possible for objects with finalizers (See 426 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6"> 427 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>) 428 * that are implemented in ways that rely on ordering control for correctness. 429 * 430 * @apiNote 431 * Finalization may occur whenever the virtual machine detects that no 432 * reference to an object will ever be stored in the heap: The garbage 433 * collector may reclaim an object even if the fields of that object are 434 * still in use, so long as the object has otherwise become unreachable. 435 * This may have surprising and undesirable effects in cases such as the 436 * following example in which the bookkeeping associated with a class is 437 * managed through array indices. Here, method {@code action} uses a 438 * {@code reachabilityFence} to ensure that the {@code Resource} object is 439 * not reclaimed before bookkeeping on an associated 440 * {@code ExternalResource} has been performed; in particular here, to 441 * ensure that the array slot holding the {@code ExternalResource} is not 442 * nulled out in method {@link Object#finalize}, which may otherwise run 443 * concurrently. 444 * 445 * <pre> {@code 446 * class Resource { 447 * private static ExternalResource[] externalResourceArray = ... 448 * 449 * int myIndex; 450 * Resource(...) { 451 * myIndex = ... 452 * externalResourceArray[myIndex] = ...; 453 * ... 454 * } 455 * protected void finalize() { 456 * externalResourceArray[myIndex] = null; 457 * ... 458 * } 459 * public void action() { 460 * try { 461 * // ... 462 * int i = myIndex; 463 * Resource.update(externalResourceArray[i]); 464 * } finally { 465 * Reference.reachabilityFence(this); 466 * } 467 * } 468 * private static void update(ExternalResource ext) { 469 * ext.status = ...; 470 * } 471 * }}</pre> 472 * 473 * Here, the invocation of {@code reachabilityFence} is nonintuitively 474 * placed <em>after</em> the call to {@code update}, to ensure that the 475 * array slot is not nulled out by {@link Object#finalize} before the 476 * update, even if the call to {@code action} was the last use of this 477 * object. This might be the case if, for example a usage in a user program 478 * had the form {@code new Resource().action();} which retains no other 479 * reference to this {@code Resource}. While probably overkill here, 480 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 481 * that it is invoked across all paths in the method. In a method with more 482 * complex control paths, you might need further precautions to ensure that 483 * {@code reachabilityFence} is encountered along all of them. 484 * 485 * <p> It is sometimes possible to better encapsulate use of 486 * {@code reachabilityFence}. Continuing the above example, if it were 487 * acceptable for the call to method {@code update} to proceed even if the 488 * finalizer had already executed (nulling out slot), then you could 489 * localize use of {@code reachabilityFence}: 490 * 491 * <pre> {@code 492 * public void action2() { 493 * // ... 494 * Resource.update(getExternalResource()); 495 * } 496 * private ExternalResource getExternalResource() { 497 * ExternalResource ext = externalResourceArray[myIndex]; 498 * Reference.reachabilityFence(this); 499 * return ext; 500 * }}</pre> 501 * 502 * <p> Method {@code reachabilityFence} is not required in constructions 503 * that themselves ensure reachability. For example, because objects that 504 * are locked cannot, in general, be reclaimed, it would suffice if all 505 * accesses of the object, in all methods of class {@code Resource} 506 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 507 * blocks. (Further, such blocks must not include infinite loops, or 508 * themselves be unreachable, which fall into the corner case exceptions to 509 * the "in general" disclaimer.) However, method {@code reachabilityFence} 510 * remains a better option in cases where this approach is not as efficient, 511 * desirable, or possible; for example because it would encounter deadlock. 512 * 513 * @param ref the reference. If {@code null}, this method has no effect. 514 * @since 9 515 */ 516 @ForceInline 517 public static void reachabilityFence(Object ref) { 518 // Does nothing. This method is annotated with @ForceInline to eliminate 519 // most of the overhead that using @DontInline would cause with the 520 // HotSpot JVM, when this fence is used in a wide variety of situations. 521 // HotSpot JVM retains the ref and does not GC it before a call to 522 // this method, because the JIT-compilers do not have GC-only safepoints. 523 } 524 }