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