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<?> 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 final 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<?> pending; 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 Reference<?> p = getPendingReferences(); 154 enqueuePendingReferences(p); 155 } 156 } 157 } 158 159 /** 160 * Blocks until GC discovers some pending references and hands them to us. 161 * 162 * @return a list of pending references linked via {@link #discovered} field 163 * with {@code null} marking the end of list. 164 */ 165 static Reference<?> getPendingReferences() { 166 Reference<?> p; 167 synchronized (lock) { 168 while ((p = pending) == null) { 169 try { 170 lock.wait(); 171 } catch (OutOfMemoryError x) { 172 // The waiting on the lock may cause an OutOfMemoryError 173 // because it may try to allocate InterruptedException object. 174 // Give other threads CPU time so they hopefully drop some live 175 // references and GC reclaims some space. 176 Thread.yield(); 177 } catch (InterruptedException x) { 178 // ignore interrupts 179 } 180 } 181 pending = null; 182 } 183 return p; 184 } 185 186 /** 187 * Enqueue a list of pending {@link Reference}s. 188 * 189 * @param p a list of pending references linked via {@link #discovered} 190 * field with {@code null} marking the end of list 191 */ 192 static void enqueuePendingReferences(Reference<?> p) { 193 while (p != null) { 194 Reference<?> r = p; 195 p = r.discovered; 196 r.discovered = null; 197 @SuppressWarnings("unchecked") 198 ReferenceQueue<Object> q = (ReferenceQueue) r.queue; 199 if (q != ReferenceQueue.NULL) q.enqueue(r); 200 } 201 } 202 203 static { 204 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 205 for (ThreadGroup tgn = tg; 206 tgn != null; 207 tg = tgn, tgn = tg.getParent()); 208 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 209 /* If there were a special system-only priority greater than 210 * MAX_PRIORITY, it would be used here 211 */ 212 handler.setPriority(Thread.MAX_PRIORITY); 213 handler.setDaemon(true); 214 handler.start(); 215 216 // provide access in SharedSecrets 217 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { 218 219 @Override 220 public boolean cleanNextEnqueuedCleanable(Cleaner cleaner) { 221 return cleaner.cleanNextEnqueued(); 222 } 223 }); 224 } 225 226 /* -- Referent accessor and setters -- */ 227 228 /** 229 * Returns this reference object's referent. If this reference object has 230 * been cleared, either by the program or by the garbage collector, then 231 * this method returns <code>null</code>. 232 * 233 * @return The object to which this reference refers, or 234 * <code>null</code> if this reference object has been cleared 235 */ 236 @HotSpotIntrinsicCandidate 237 public T get() { 238 return this.referent; 239 } 240 241 /** 242 * Clears this reference object. Invoking this method will not cause this 243 * object to be enqueued. 244 * 245 * <p> This method is invoked only by Java code; when the garbage collector 246 * clears references it does so directly, without invoking this method. 247 */ 248 public void clear() { 249 this.referent = null; 250 } 251 252 253 /* -- Queue operations -- */ 254 255 /** 256 * Tells whether or not this reference object has been enqueued, either by 257 * the program or by the garbage collector. If this reference object was 258 * not registered with a queue when it was created, then this method will 259 * always return <code>false</code>. 260 * 261 * @return <code>true</code> if and only if this reference object has 262 * been enqueued 263 */ 264 public boolean isEnqueued() { 265 return (this.queue == ReferenceQueue.ENQUEUED); 266 } 267 268 /** 269 * Adds this reference object to the queue with which it is registered, 270 * if any. 271 * 272 * <p> This method is invoked only by Java code; when the garbage collector 273 * enqueues references it does so directly, without invoking this method. 274 * 275 * @return <code>true</code> if this reference object was successfully 276 * enqueued; <code>false</code> if it was already enqueued or if 277 * it was not registered with a queue when it was created 278 */ 279 public boolean enqueue() { 280 return this.queue.enqueue(this); 281 } 282 283 284 /* -- Constructors -- */ 285 286 Reference(T referent) { 287 this(referent, null); 288 } 289 290 Reference(T referent, ReferenceQueue<? super T> queue) { 291 this.referent = referent; 292 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 293 } 294 295 /** 296 * Ensures that the object referenced by the given reference remains 297 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 298 * regardless of any prior actions of the program that might otherwise cause 299 * the object to become unreachable; thus, the referenced object is not 300 * reclaimable by garbage collection at least until after the invocation of 301 * this method. Invocation of this method does not itself initiate garbage 302 * collection or finalization. 303 * 304 * <p> This method establishes an ordering for 305 * <a href="package-summary.html#reachability"><em>strong reachability</em></a> 306 * with respect to garbage collection. It controls relations that are 307 * otherwise only implicit in a program -- the reachability conditions 308 * triggering garbage collection. This method is designed for use in 309 * uncommon situations of premature finalization where using 310 * {@code synchronized} blocks or methods, or using other synchronization 311 * facilities are not possible or do not provide the desired control. This 312 * method is applicable only when reclamation may have visible effects, 313 * which is possible for objects with finalizers (See 314 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6"> 315 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>) 316 * that are implemented in ways that rely on ordering control for correctness. 317 * 318 * @apiNote 319 * Finalization may occur whenever the virtual machine detects that no 320 * reference to an object will ever be stored in the heap: The garbage 321 * collector may reclaim an object even if the fields of that object are 322 * still in use, so long as the object has otherwise become unreachable. 323 * This may have surprising and undesirable effects in cases such as the 324 * following example in which the bookkeeping associated with a class is 325 * managed through array indices. Here, method {@code action} uses a 326 * {@code reachabilityFence} to ensure that the {@code Resource} object is 327 * not reclaimed before bookkeeping on an associated 328 * {@code ExternalResource} has been performed; in particular here, to 329 * ensure that the array slot holding the {@code ExternalResource} is not 330 * nulled out in method {@link Object#finalize}, which may otherwise run 331 * concurrently. 332 * 333 * <pre> {@code 334 * class Resource { 335 * private static ExternalResource[] externalResourceArray = ... 336 * 337 * int myIndex; 338 * Resource(...) { 339 * myIndex = ... 340 * externalResourceArray[myIndex] = ...; 341 * ... 342 * } 343 * protected void finalize() { 344 * externalResourceArray[myIndex] = null; 345 * ... 346 * } 347 * public void action() { 348 * try { 349 * // ... 350 * int i = myIndex; 351 * Resource.update(externalResourceArray[i]); 352 * } finally { 353 * Reference.reachabilityFence(this); 354 * } 355 * } 356 * private static void update(ExternalResource ext) { 357 * ext.status = ...; 358 * } 359 * }}</pre> 360 * 361 * Here, the invocation of {@code reachabilityFence} is nonintuitively 362 * placed <em>after</em> the call to {@code update}, to ensure that the 363 * array slot is not nulled out by {@link Object#finalize} before the 364 * update, even if the call to {@code action} was the last use of this 365 * object. This might be the case if, for example a usage in a user program 366 * had the form {@code new Resource().action();} which retains no other 367 * reference to this {@code Resource}. While probably overkill here, 368 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 369 * that it is invoked across all paths in the method. In a method with more 370 * complex control paths, you might need further precautions to ensure that 371 * {@code reachabilityFence} is encountered along all of them. 372 * 373 * <p> It is sometimes possible to better encapsulate use of 374 * {@code reachabilityFence}. Continuing the above example, if it were 375 * acceptable for the call to method {@code update} to proceed even if the 376 * finalizer had already executed (nulling out slot), then you could 377 * localize use of {@code reachabilityFence}: 378 * 379 * <pre> {@code 380 * public void action2() { 381 * // ... 382 * Resource.update(getExternalResource()); 383 * } 384 * private ExternalResource getExternalResource() { 385 * ExternalResource ext = externalResourceArray[myIndex]; 386 * Reference.reachabilityFence(this); 387 * return ext; 388 * }}</pre> 389 * 390 * <p> Method {@code reachabilityFence} is not required in constructions 391 * that themselves ensure reachability. For example, because objects that 392 * are locked cannot, in general, be reclaimed, it would suffice if all 393 * accesses of the object, in all methods of class {@code Resource} 394 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 395 * blocks. (Further, such blocks must not include infinite loops, or 396 * themselves be unreachable, which fall into the corner case exceptions to 397 * the "in general" disclaimer.) However, method {@code reachabilityFence} 398 * remains a better option in cases where this approach is not as efficient, 399 * desirable, or possible; for example because it would encounter deadlock. 400 * 401 * @param ref the reference. If {@code null}, this method has no effect. 402 * @since 9 403 */ 404 @DontInline 405 public static void reachabilityFence(Object ref) { 406 // Does nothing, because this method is annotated with @DontInline 407 // HotSpot needs to retain the ref and not GC it before a call to this 408 // method 409 } 410 411 }