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