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