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