1 /* 2 * Copyright (c) 1997, 2022, 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.misc.Unsafe; 29 import jdk.internal.vm.annotation.ForceInline; 30 import jdk.internal.vm.annotation.IntrinsicCandidate; 31 import jdk.internal.access.JavaLangRefAccess; 32 import jdk.internal.access.SharedSecrets; 33 import jdk.internal.ref.Cleaner; 34 35 import java.util.Objects; 36 37 /** 38 * Abstract base class for reference objects. This class defines the 39 * operations common to all reference objects. Because reference objects are 40 * implemented in close cooperation with the garbage collector, this class may 41 * not be subclassed directly. 42 * <p> 43 * The referent must be an {@linkplain Objects#hasIdentity(Object) identity object}. 44 * Attempts to create a reference to a value object result in an {@link IdentityException}. 45 * @param <T> the type of the referent 46 * 47 * @author Mark Reinhold 48 * @since 1.2 49 * @sealedGraph 50 */ 51 52 public abstract sealed class Reference<T> 53 permits PhantomReference, SoftReference, WeakReference, FinalReference { 54 55 /* The state of a Reference object is characterized by two attributes. It 56 * may be either "active", "pending", or "inactive". It may also be 57 * either "registered", "enqueued", "dequeued", or "unregistered". 58 * 59 * Active: Subject to special treatment by the garbage collector. Some 60 * time after the collector detects that the reachability of the 61 * referent has changed to the appropriate state, the collector 62 * "notifies" the reference, changing the state to either "pending" or 63 * "inactive". 64 * referent != null; discovered = null, or in GC discovered list. 65 * 66 * Pending: An element of the pending-Reference list, waiting to be 67 * processed by the ReferenceHandler thread. The pending-Reference 68 * list is linked through the discovered fields of references in the 69 * list. 70 * referent = null; discovered = next element in pending-Reference list. 71 * 72 * Inactive: Neither Active nor Pending. 73 * referent = null. 74 * 75 * Registered: Associated with a queue when created, and not yet added 76 * to the queue. 77 * queue = the associated queue. 78 * 79 * Enqueued: Added to the associated queue, and not yet removed. 80 * queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to 81 * indicate end of list. 82 * 83 * Dequeued: Added to the associated queue and then removed. 84 * queue = ReferenceQueue.NULL; next = this. 85 * 86 * Unregistered: Not associated with a queue when created. 87 * queue = ReferenceQueue.NULL. 88 * 89 * The collector only needs to examine the referent field and the 90 * discovered field to determine whether a (non-FinalReference) Reference 91 * object needs special treatment. If the referent is non-null and not 92 * known to be live, then it may need to be discovered for possible later 93 * notification. But if the discovered field is non-null, then it has 94 * already been discovered. 95 * 96 * FinalReference (which exists to support finalization) differs from 97 * other references, because a FinalReference is not cleared when 98 * notified. The referent being null or not cannot be used to distinguish 99 * between the active state and pending or inactive states. However, 100 * FinalReferences do not support enqueue(). Instead, the next field of a 101 * FinalReference object is set to "this" when it is added to the 102 * pending-Reference list. The use of "this" as the value of next in the 103 * enqueued and dequeued states maintains the non-active state. An 104 * additional check that the next field is null is required to determine 105 * that a FinalReference object is active. 106 * 107 * Initial states: 108 * [active/registered] 109 * [active/unregistered] [1] 110 * 111 * Transitions: 112 * clear [2] 113 * [active/registered] -------> [inactive/registered] 114 * | | 115 * | | enqueue 116 * | GC enqueue [2] | 117 * | -----------------| 118 * | | 119 * v | 120 * [pending/registered] --- v 121 * | | ReferenceHandler 122 * | enqueue [2] |---> [inactive/enqueued] 123 * v | | 124 * [pending/enqueued] --- | 125 * | | poll/remove 126 * | poll/remove | + clear [4] 127 * | | 128 * v ReferenceHandler v 129 * [pending/dequeued] ------> [inactive/dequeued] 130 * 131 * 132 * clear/enqueue/GC [3] 133 * [active/unregistered] ------ 134 * | | 135 * | GC | 136 * | |--> [inactive/unregistered] 137 * v | 138 * [pending/unregistered] ------ 139 * ReferenceHandler 140 * 141 * Terminal states: 142 * [inactive/dequeued] 143 * [inactive/unregistered] 144 * 145 * Unreachable states (because enqueue also clears): 146 * [active/enqueued] 147 * [active/dequeued] 148 * 149 * [1] Unregistered is not permitted for FinalReferences. 150 * 151 * [2] These transitions are not possible for FinalReferences, making 152 * [pending/enqueued], [pending/dequeued], and [inactive/registered] 153 * unreachable. 154 * 155 * [3] The garbage collector may directly transition a Reference 156 * from [active/unregistered] to [inactive/unregistered], 157 * bypassing the pending-Reference list. 158 * 159 * [4] The queue handler for FinalReferences also clears the reference. 160 */ 161 162 private T referent; /* Treated specially by GC */ 163 164 /* The queue this reference gets enqueued to by GC notification or by 165 * calling enqueue(). 166 * 167 * When registered: the queue with which this reference is registered. 168 * enqueued: ReferenceQueue.ENQUEUE 169 * dequeued: ReferenceQueue.NULL 170 * unregistered: ReferenceQueue.NULL 171 */ 172 volatile ReferenceQueue<? super T> queue; 173 174 /* The link in a ReferenceQueue's list of Reference objects. 175 * 176 * When registered: null 177 * enqueued: next element in queue (or this if last) 178 * dequeued: this (marking FinalReferences as inactive) 179 * unregistered: null 180 */ 181 @SuppressWarnings("rawtypes") 182 volatile Reference next; 183 184 /* Used by the garbage collector to accumulate Reference objects that need 185 * to be revisited in order to decide whether they should be notified. 186 * Also used as the link in the pending-Reference list. The discovered 187 * field and the next field are distinct to allow the enqueue() method to 188 * be applied to a Reference object while it is either in the 189 * pending-Reference list or in the garbage collector's discovered set. 190 * 191 * When active: null or next element in a discovered reference list 192 * maintained by the GC (or this if last) 193 * pending: next element in the pending-Reference list (null if last) 194 * inactive: null 195 */ 196 private transient Reference<?> discovered; 197 198 199 /* High-priority thread to enqueue pending References 200 */ 201 private static class ReferenceHandler extends Thread { 202 ReferenceHandler(ThreadGroup g, String name) { 203 super(g, null, name, 0, false); 204 } 205 206 public void run() { 207 // pre-load and initialize Cleaner class so that we don't 208 // get into trouble later in the run loop if there's 209 // memory shortage while loading/initializing it lazily. 210 Unsafe.getUnsafe().ensureClassInitialized(Cleaner.class); 211 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<?> 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 /* 234 * Enqueue a Reference taken from the pending list. Calling this method 235 * takes us from the Reference<?> domain of the pending list elements to 236 * having a Reference<T> with a correspondingly typed queue. 237 */ 238 private void enqueueFromPending() { 239 var q = queue; 240 if (q != ReferenceQueue.NULL) q.enqueue(this); 241 } 242 243 private static final Object processPendingLock = new Object(); 244 private static boolean processPendingActive = false; 245 246 private static void processPendingReferences() { 247 // Only the singleton reference processing thread calls 248 // waitForReferencePendingList() and getAndClearReferencePendingList(). 249 // These are separate operations to avoid a race with other threads 250 // that are calling waitForReferenceProcessing(). 251 waitForReferencePendingList(); 252 Reference<?> pendingList; 253 synchronized (processPendingLock) { 254 pendingList = getAndClearReferencePendingList(); 255 processPendingActive = true; 256 } 257 while (pendingList != null) { 258 Reference<?> ref = pendingList; 259 pendingList = ref.discovered; 260 ref.discovered = null; 261 262 if (ref instanceof Cleaner) { 263 ((Cleaner)ref).clean(); 264 // Notify any waiters that progress has been made. 265 // This improves latency for nio.Bits waiters, which 266 // are the only important ones. 267 synchronized (processPendingLock) { 268 processPendingLock.notifyAll(); 269 } 270 } else { 271 ref.enqueueFromPending(); 272 } 273 } 274 // Notify any waiters of completion of current round. 275 synchronized (processPendingLock) { 276 processPendingActive = false; 277 processPendingLock.notifyAll(); 278 } 279 } 280 281 // Wait for progress in reference processing. 282 // 283 // Returns true after waiting (for notification from the reference 284 // processing thread) if either (1) the VM has any pending 285 // references, or (2) the reference processing thread is 286 // processing references. Otherwise, returns false immediately. 287 private static boolean waitForReferenceProcessing() 288 throws InterruptedException 289 { 290 synchronized (processPendingLock) { 291 if (processPendingActive || hasReferencePendingList()) { 292 // Wait for progress, not necessarily completion. 293 processPendingLock.wait(); 294 return true; 295 } else { 296 return false; 297 } 298 } 299 } 300 301 /** 302 * Start the Reference Handler thread as a daemon thread. 303 */ 304 static void startReferenceHandlerThread(ThreadGroup tg) { 305 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 306 /* If there were a special system-only priority greater than 307 * MAX_PRIORITY, it would be used here 308 */ 309 handler.setPriority(Thread.MAX_PRIORITY); 310 handler.setDaemon(true); 311 handler.start(); 312 } 313 314 static { 315 // provide access in SharedSecrets 316 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 317 @Override 318 public void startThreads() { 319 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 320 for (ThreadGroup tgn = tg; 321 tgn != null; 322 tg = tgn, tgn = tg.getParent()); 323 Reference.startReferenceHandlerThread(tg); 324 Finalizer.startFinalizerThread(tg); 325 } 326 327 @Override 328 public boolean waitForReferenceProcessing() 329 throws InterruptedException 330 { 331 return Reference.waitForReferenceProcessing(); 332 } 333 334 @Override 335 public void runFinalization() { 336 Finalizer.runFinalization(); 337 } 338 339 @Override 340 public <T> ReferenceQueue<T> newNativeReferenceQueue() { 341 return new NativeReferenceQueue<T>(); 342 } 343 }); 344 } 345 346 /* -- Referent accessor and setters -- */ 347 348 /** 349 * Returns this reference object's referent. If this reference object has 350 * been cleared, either by the program or by the garbage collector, then 351 * this method returns {@code null}. 352 * 353 * @apiNote 354 * This method returns a strong reference to the referent. This may cause 355 * the garbage collector to treat it as strongly reachable until some later 356 * collection cycle. The {@link #refersTo(Object) refersTo} method can be 357 * used to avoid such strengthening when testing whether some object is 358 * the referent of a reference object; that is, use {@code ref.refersTo(obj)} 359 * rather than {@code ref.get() == obj}. 360 * 361 * @return The object to which this reference refers, or 362 * {@code null} if this reference object has been cleared 363 * @see #refersTo 364 */ 365 @IntrinsicCandidate 366 public T get() { 367 return this.referent; 368 } 369 370 /** 371 * Tests if the referent of this reference object is {@code obj}. 372 * Using a {@code null} {@code obj} returns {@code true} if the 373 * reference object has been cleared. 374 * 375 * @param obj the object to compare with this reference object's referent 376 * @return {@code true} if {@code obj} is the referent of this reference object 377 * @since 16 378 */ 379 public final boolean refersTo(T obj) { 380 return refersToImpl(obj); 381 } 382 383 /* Implementation of refersTo(), overridden for phantom references. 384 * This method exists only to avoid making refersTo0() virtual. Making 385 * refersTo0() virtual has the undesirable effect of C2 often preferring 386 * to call the native implementation over the intrinsic. 387 */ 388 boolean refersToImpl(T obj) { 389 return refersTo0(obj); 390 } 391 392 @IntrinsicCandidate 393 private native boolean refersTo0(Object o); 394 395 /** 396 * Clears this reference object. Invoking this method will not cause this 397 * object to be enqueued. 398 * 399 * <p> This method is invoked only by Java code; when the garbage collector 400 * clears references it does so directly, without invoking this method. 401 */ 402 public void clear() { 403 clear0(); 404 } 405 406 /* Implementation of clear(), also used by enqueue(). A simple 407 * assignment of the referent field won't do for some garbage 408 * collectors. 409 */ 410 private native void clear0(); 411 412 /* -- Operations on inactive FinalReferences -- */ 413 414 /* These functions are only used by FinalReference, and must only be 415 * called after the reference becomes inactive. While active, a 416 * FinalReference is considered weak but the referent is not normally 417 * accessed. Once a FinalReference becomes inactive it is considered a 418 * strong reference. These functions are used to bypass the 419 * corresponding weak implementations, directly accessing the referent 420 * field with strong semantics. 421 */ 422 423 /** 424 * Load referent with strong semantics. 425 */ 426 T getFromInactiveFinalReference() { 427 assert this instanceof FinalReference; 428 assert next != null; // I.e. FinalReference is inactive 429 return this.referent; 430 } 431 432 /** 433 * Clear referent with strong semantics. 434 */ 435 void clearInactiveFinalReference() { 436 assert this instanceof FinalReference; 437 assert next != null; // I.e. FinalReference is inactive 438 this.referent = null; 439 } 440 441 /* -- Queue operations -- */ 442 443 /** 444 * Tests if this reference object is in its associated queue, if any. 445 * This method returns {@code true} only if all of the following conditions 446 * are met: 447 * <ul> 448 * <li>this reference object was registered with a queue when it was created; and 449 * <li>the garbage collector has added this reference object to the queue 450 * or {@link #enqueue()} is called; and 451 * <li>this reference object is not yet removed from the queue. 452 * </ul> 453 * Otherwise, this method returns {@code false}. 454 * This method may return {@code false} if this reference object has been cleared 455 * but not enqueued due to the race condition. 456 * 457 * @deprecated 458 * This method was originally specified to test if a reference object has 459 * been cleared and enqueued but was never implemented to do this test. 460 * This method could be misused due to the inherent race condition 461 * or without an associated {@code ReferenceQueue}. 462 * An application relying on this method to release critical resources 463 * could cause serious performance issue. 464 * An application should use {@link ReferenceQueue} to reliably determine 465 * what reference objects that have been enqueued or 466 * {@link #refersTo(Object) refersTo(null)} to determine if this reference 467 * object has been cleared. 468 * 469 * @return {@code true} if and only if this reference object is 470 * in its associated queue (if any). 471 */ 472 @Deprecated(since="16") 473 public boolean isEnqueued() { 474 return (this.queue == ReferenceQueue.ENQUEUED); 475 } 476 477 /** 478 * Clears this reference object and adds it to the queue with which 479 * it is registered, if any. 480 * 481 * <p> This method is invoked only by Java code; when the garbage collector 482 * enqueues references it does so directly, without invoking this method. 483 * 484 * @return {@code true} if this reference object was successfully 485 * enqueued; {@code false} if it was already enqueued or if 486 * it was not registered with a queue when it was created 487 */ 488 public boolean enqueue() { 489 clear0(); // Intentionally clear0() rather than clear() 490 return this.queue.enqueue(this); 491 } 492 493 /** 494 * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be 495 * meaningfully cloned. Construct a new {@code Reference} instead. 496 * 497 * @return never returns normally 498 * @throws CloneNotSupportedException always 499 * 500 * @since 11 501 */ 502 @Override 503 protected Object clone() throws CloneNotSupportedException { 504 throw new CloneNotSupportedException(); 505 } 506 507 /* -- Constructors -- */ 508 509 Reference(T referent) { 510 this(referent, null); 511 } 512 513 Reference(T referent, ReferenceQueue<? super T> queue) { 514 if (referent != null) { 515 Objects.requireIdentity(referent); 516 } 517 this.referent = referent; 518 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 519 } 520 521 /** 522 * Ensures that the object referenced by the given reference remains 523 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 524 * regardless of any prior actions of the program that might otherwise cause 525 * the object to become unreachable; thus, the referenced object is not 526 * reclaimable by garbage collection at least until after the invocation of 527 * this method. Invocation of this method does not itself initiate garbage 528 * collection or finalization. 529 * 530 * <p> This method establishes an ordering for <em>strong reachability</em> 531 * with respect to garbage collection. It controls relations that are 532 * otherwise only implicit in a program -- the reachability conditions 533 * triggering garbage collection. This method is designed for use in 534 * uncommon situations of premature finalization where using 535 * {@code synchronized} blocks or methods, or using other synchronization 536 * facilities are not possible or do not provide the desired control. This 537 * method is applicable only when reclamation may have visible effects, 538 * which is possible for objects with finalizers (See Section {@jls 12.6} 539 * of <cite>The Java Language Specification</cite>) that 540 * are implemented in ways that rely on ordering control for 541 * correctness. 542 * 543 * @apiNote 544 * Finalization may occur whenever the virtual machine detects that no 545 * reference to an object will ever be stored in the heap: The garbage 546 * collector may reclaim an object even if the fields of that object are 547 * still in use, so long as the object has otherwise become unreachable. 548 * This may have surprising and undesirable effects in cases such as the 549 * following example in which the bookkeeping associated with a class is 550 * managed through array indices. Here, method {@code action} uses a 551 * {@code reachabilityFence} to ensure that the {@code Resource} object is 552 * not reclaimed before bookkeeping on an associated 553 * {@code ExternalResource} has been performed; in particular here, to 554 * ensure that the array slot holding the {@code ExternalResource} is not 555 * nulled out in method {@link Object#finalize}, which may otherwise run 556 * concurrently. 557 * 558 * <pre> {@code 559 * class Resource { 560 * private static ExternalResource[] externalResourceArray = ... 561 * 562 * int myIndex; 563 * Resource(...) { 564 * myIndex = ... 565 * externalResourceArray[myIndex] = ...; 566 * ... 567 * } 568 * protected void finalize() { 569 * externalResourceArray[myIndex] = null; 570 * ... 571 * } 572 * public void action() { 573 * try { 574 * // ... 575 * int i = myIndex; 576 * Resource.update(externalResourceArray[i]); 577 * } finally { 578 * Reference.reachabilityFence(this); 579 * } 580 * } 581 * private static void update(ExternalResource ext) { 582 * ext.status = ...; 583 * } 584 * }}</pre> 585 * 586 * Here, the invocation of {@code reachabilityFence} is nonintuitively 587 * placed <em>after</em> the call to {@code update}, to ensure that the 588 * array slot is not nulled out by {@link Object#finalize} before the 589 * update, even if the call to {@code action} was the last use of this 590 * object. This might be the case if, for example a usage in a user program 591 * had the form {@code new Resource().action();} which retains no other 592 * reference to this {@code Resource}. While probably overkill here, 593 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 594 * that it is invoked across all paths in the method. In a method with more 595 * complex control paths, you might need further precautions to ensure that 596 * {@code reachabilityFence} is encountered along all of them. 597 * 598 * <p> It is sometimes possible to better encapsulate use of 599 * {@code reachabilityFence}. Continuing the above example, if it were 600 * acceptable for the call to method {@code update} to proceed even if the 601 * finalizer had already executed (nulling out slot), then you could 602 * localize use of {@code reachabilityFence}: 603 * 604 * <pre> {@code 605 * public void action2() { 606 * // ... 607 * Resource.update(getExternalResource()); 608 * } 609 * private ExternalResource getExternalResource() { 610 * ExternalResource ext = externalResourceArray[myIndex]; 611 * Reference.reachabilityFence(this); 612 * return ext; 613 * }}</pre> 614 * 615 * <p> Method {@code reachabilityFence} is not required in constructions 616 * that themselves ensure reachability. For example, because objects that 617 * are locked cannot, in general, be reclaimed, it would suffice if all 618 * accesses of the object, in all methods of class {@code Resource} 619 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 620 * blocks. (Further, such blocks must not include infinite loops, or 621 * themselves be unreachable, which fall into the corner case exceptions to 622 * the "in general" disclaimer.) However, method {@code reachabilityFence} 623 * remains a better option in cases where this approach is not as efficient, 624 * desirable, or possible; for example because it would encounter deadlock. 625 * 626 * @param ref the reference. If {@code null}, this method has no effect. 627 * @since 9 628 */ 629 @ForceInline 630 public static void reachabilityFence(Object ref) { 631 // Does nothing. This method is annotated with @ForceInline to eliminate 632 // most of the overhead that using @DontInline would cause with the 633 // HotSpot JVM, when this fence is used in a wide variety of situations. 634 // HotSpot JVM retains the ref and does not GC it before a call to 635 // this method, because the JIT-compilers do not have GC-only safepoints. 636 } 637 } --- EOF ---