1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.lang.ref; 28 29 import dalvik.annotation.optimization.FastNative; 30 31 32 /** 33 * Abstract base class for reference objects. This class defines the 34 * operations common to all reference objects. Because reference objects are 35 * implemented in close cooperation with the garbage collector, this class may 36 * not be subclassed directly. 37 * 38 * @author Mark Reinhold 39 * @since 1.2 40 */ 41 42 public abstract class Reference<T> { 43 // BEGIN Android-changed: Reimplemented to accommodate a different GC and compiler. 44 // ClassLinker knows about the fields of this class. 45 // Backported refersTo() from OpenJDK 16. 46 47 /** 48 * Forces JNI path. 49 * If GC is not in progress (ie: not going through slow path), the referent 50 * can be quickly returned through intrinsic without passing through JNI. 51 * This flag forces the JNI path so that it can be tested and benchmarked. 52 */ 53 private static boolean disableIntrinsic = false; 54 55 /** 56 * Slow path flag for the reference processor. 57 * Used by the reference processor to determine whether or not the referent 58 * can be immediately returned. Because the referent might get swept during 59 * GC, the slow path, which passes through JNI, must be taken. 60 * After initialization, this is only accessed by native code. It is not 61 * used with the concurrent copying collector. It is enabled with mutators 62 * suspended, but disabled asynchronously. 63 */ 64 private static boolean slowPathEnabled = false; 65 66 // Treated specially by GC. ART's ClassLinker::LinkFieldsHelper::LinkFields() 67 // knows this is the alphabetically last non-static field. 68 // We assume that Reference.get() and Reference.clear() are intended to be 69 // callable concurrently, and thus referent accesses should be treated as 70 // volatile everywhere. 71 volatile T referent; 72 73 final ReferenceQueue<? super T> queue; 74 75 /* 76 * This field forms a singly-linked list of reference objects that have 77 * been enqueued. The queueNext field is non-null if and only if this 78 * reference has been enqueued. After this reference has been enqueued and 79 * before it has been removed from its queue, the queueNext field points 80 * to the next reference on the queue. The last reference on a queue 81 * points to itself. Once this reference has been removed from the 82 * reference queue, the queueNext field points to the 83 * ReferenceQueue.sQueueNextUnenqueued sentinel reference object for the 84 * rest of this reference's lifetime. 85 * <p> 86 * Access to the queueNext field is guarded by synchronization on a lock 87 * internal to 'queue'. 88 */ 89 Reference queueNext; 90 91 /** 92 * The pendingNext field is initially set by the GC. After the GC forms a 93 * complete circularly linked list, the list is handed off to the 94 * ReferenceQueueDaemon using the ReferenceQueue.class lock. The 95 * ReferenceQueueDaemon can then read the pendingNext fields without 96 * additional synchronization. 97 */ 98 Reference<?> pendingNext; 99 100 /* -- Referent accessor and setters -- */ 101 102 /** 103 * Returns this reference object's referent. If this reference object has 104 * been cleared, either by the program or by the garbage collector, then 105 * this method returns <code>null</code>. 106 * 107 * @return The object to which this reference refers, or 108 * <code>null</code> if this reference object has been cleared 109 */ get()110 public T get() { 111 return getReferent(); 112 } 113 114 @FastNative getReferent()115 private final native T getReferent(); 116 117 /** 118 * Tests if the referent of this reference object is {@code obj}. 119 * Using a {@code null} {@code obj} returns {@code true} if the 120 * reference object has been cleared. Prefer this to a comparison 121 * with the result of {@code get}. 122 * 123 * @param obj the object to compare with this reference object's referent 124 * @return {@code true} if {@code obj} is the referent of this reference object 125 */ refersTo(T obj)126 public final boolean refersTo(T obj) { 127 return refersTo0(obj); 128 } 129 130 /* Implementation of refersTo(). */ 131 @FastNative refersTo0(Object o)132 private final native boolean refersTo0(Object o); 133 134 /** 135 * Clears this reference object. Invoking this method will not cause this 136 * object to be enqueued. 137 * 138 * <p> This method is invoked only by Java code; when the garbage collector 139 * clears references it does so directly, without invoking this method. 140 */ clear()141 public void clear() { 142 clearReferent(); 143 } 144 145 // Direct access to the referent is prohibited, clearReferent blocks and set 146 // the referent to null when it is safe to do so. 147 @FastNative clearReferent()148 native void clearReferent(); 149 150 /* -- Queue operations -- */ 151 152 // Android-changed: deprecate since 9. 153 // @Deprecated(since="16") 154 /** 155 * Tests if this reference object is in its associated queue, if any. 156 * This method returns {@code true} only if all of the following conditions 157 * are met: 158 * <ul> 159 * <li>this reference object was registered with a queue when it was created; and 160 * <li>the garbage collector has added this reference object to the queue 161 * or {@link #enqueue()} is called; and 162 * <li>this reference object is not yet removed from the queue. 163 * </ul> 164 * Otherwise, this method returns {@code false}. 165 * This method may return {@code false} if this reference object has been cleared 166 * but not enqueued due to the race condition. 167 * 168 * @deprecated 169 * This method was never implemented to test if a reference object has 170 * been cleared and enqueued as it was previously specified since 1.2. 171 * This method could be misused due to the inherent race condition 172 * or without an associated {@code ReferenceQueue}. 173 * An application relying on this method to release critical resources 174 * could cause serious performance issue. 175 * An application should use {@link ReferenceQueue} to reliably determine 176 * what reference objects that have been enqueued or 177 * {@code refersTo(null)} to determine if this reference 178 * object has been cleared. 179 * 180 * @return {@code true} if and only if this reference object is 181 * in its associated queue (if any). 182 */ 183 @Deprecated(since="9") isEnqueued()184 public boolean isEnqueued() { 185 // Contrary to what the documentation says, this method returns false 186 // after this reference object has been removed from its queue 187 // (b/26647823). ReferenceQueue.isEnqueued preserves this historically 188 // incorrect behavior. 189 return queue != null && queue.isEnqueued(this); 190 } 191 192 /** 193 * Adds this reference object to the queue with which it is registered, 194 * if any. 195 * 196 * <p> This method is invoked only by Java code; when the garbage collector 197 * enqueues references it does so directly, without invoking this method. 198 * 199 * @return <code>true</code> if this reference object was successfully 200 * enqueued; <code>false</code> if it was already enqueued or if 201 * it was not registered with a queue when it was created 202 */ enqueue()203 public boolean enqueue() { 204 return queue != null && queue.enqueue(this); 205 } 206 207 /** 208 * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be 209 * meaningfully cloned. Construct a new {@code Reference} instead. 210 * 211 * @return never returns normally 212 * @throws CloneNotSupportedException always 213 * 214 * @since 11 215 */ 216 @Override clone()217 protected Object clone() throws CloneNotSupportedException { 218 throw new CloneNotSupportedException(); 219 } 220 221 /* -- Constructors -- */ 222 Reference(T referent)223 Reference(T referent) { 224 this(referent, null); 225 } 226 Reference(T referent, ReferenceQueue<? super T> queue)227 Reference(T referent, ReferenceQueue<? super T> queue) { 228 this.referent = referent; 229 this.queue = queue; 230 } 231 // END Android-changed: Reimplemented to accommodate a different GC and compiler. 232 233 // BEGIN Android-added: reachabilityFence() from upstream OpenJDK9+181. 234 // The actual implementation differs from OpenJDK9. 235 /** 236 * Ensures that the object referenced by the given reference remains 237 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 238 * regardless of any prior actions of the program that might otherwise cause 239 * the object to become unreachable; thus, the referenced object is not 240 * reclaimable by garbage collection at least until after the invocation of 241 * this method. Invocation of this method does not itself initiate garbage 242 * collection or finalization. 243 * 244 * <p> This method establishes an ordering for 245 * <a href="package-summary.html#reachability"><em>strong reachability</em></a> 246 * with respect to garbage collection. It controls relations that are 247 * otherwise only implicit in a program -- the reachability conditions 248 * triggering garbage collection. This method is designed for use in 249 * uncommon situations of premature finalization where using 250 * {@code synchronized} blocks or methods, or using other synchronization 251 * facilities are not possible or do not provide the desired control. This 252 * method is applicable only when reclamation may have visible effects, 253 * which is possible for objects with finalizers (See 254 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6"> 255 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>) 256 * that are implemented in ways that rely on ordering control for correctness. 257 * 258 * @apiNote 259 * Finalization may occur whenever the virtual machine detects that no 260 * reference to an object will ever be stored in the heap: The garbage 261 * collector may reclaim an object even if the fields of that object are 262 * still in use, so long as the object has otherwise become unreachable. 263 * This may have surprising and undesirable effects in cases such as the 264 * following example in which the bookkeeping associated with a class is 265 * managed through array indices. Here, method {@code action} uses a 266 * {@code reachabilityFence} to ensure that the {@code Resource} object is 267 * not reclaimed before bookkeeping on an associated 268 * {@code ExternalResource} has been performed; in particular here, to 269 * ensure that the array slot holding the {@code ExternalResource} is not 270 * nulled out in method {@link Object#finalize}, which may otherwise run 271 * concurrently. 272 * 273 * <pre> {@code 274 * class Resource { 275 * private static ExternalResource[] externalResourceArray = ... 276 * 277 * int myIndex; 278 * Resource(...) { 279 * myIndex = ... 280 * externalResourceArray[myIndex] = ...; 281 * ... 282 * } 283 * protected void finalize() { 284 * externalResourceArray[myIndex] = null; 285 * ... 286 * } 287 * public void action() { 288 * try { 289 * // ... 290 * int i = myIndex; 291 * Resource.update(externalResourceArray[i]); 292 * } finally { 293 * Reference.reachabilityFence(this); 294 * } 295 * } 296 * private static void update(ExternalResource ext) { 297 * ext.status = ...; 298 * } 299 * }}</pre> 300 * 301 * Here, the invocation of {@code reachabilityFence} is nonintuitively 302 * placed <em>after</em> the call to {@code update}, to ensure that the 303 * array slot is not nulled out by {@link Object#finalize} before the 304 * update, even if the call to {@code action} was the last use of this 305 * object. This might be the case if, for example a usage in a user program 306 * had the form {@code new Resource().action();} which retains no other 307 * reference to this {@code Resource}. While probably overkill here, 308 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 309 * that it is invoked across all paths in the method. In a method with more 310 * complex control paths, you might need further precautions to ensure that 311 * {@code reachabilityFence} is encountered along all of them. 312 * 313 * <p> It is sometimes possible to better encapsulate use of 314 * {@code reachabilityFence}. Continuing the above example, if it were 315 * acceptable for the call to method {@code update} to proceed even if the 316 * finalizer had already executed (nulling out slot), then you could 317 * localize use of {@code reachabilityFence}: 318 * 319 * <pre> {@code 320 * public void action2() { 321 * // ... 322 * Resource.update(getExternalResource()); 323 * } 324 * private ExternalResource getExternalResource() { 325 * ExternalResource ext = externalResourceArray[myIndex]; 326 * Reference.reachabilityFence(this); 327 * return ext; 328 * }}</pre> 329 * 330 * <p> Method {@code reachabilityFence} is not required in constructions 331 * that themselves ensure reachability. For example, because objects that 332 * are locked cannot, in general, be reclaimed, it would suffice if all 333 * accesses of the object, in all methods of class {@code Resource} 334 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 335 * blocks. (Further, such blocks must not include infinite loops, or 336 * themselves be unreachable, which fall into the corner case exceptions to 337 * the "in general" disclaimer.) However, method {@code reachabilityFence} 338 * remains a better option in cases where this approach is not as efficient, 339 * desirable, or possible; for example because it would encounter deadlock. 340 * 341 * @param ref the reference. If {@code null}, this method has no effect. 342 * @since 9 343 */ 344 // @DontInline reachabilityFence(Object ref)345 public static void reachabilityFence(Object ref) { 346 // This code is usually replaced by much faster intrinsic implementations. 347 // It will be executed for tests run with the access checks interpreter in 348 // ART, e.g. with --verify-soft-fail. Since this is a volatile store, it 349 // cannot easily be moved up past prior accesses, even if this method is 350 // inlined. 351 SinkHolder.sink = ref; 352 // Leaving SinkHolder set to ref is unpleasant, since it keeps ref live 353 // until the next reachabilityFence call. This causes e.g. 036-finalizer 354 // to fail. Clear it again in a way that's unlikely to be optimizable. 355 // The fact that finalize_count is volatile makes it hard to move the test up. 356 if (SinkHolder.finalize_count == 0) { 357 SinkHolder.sink = null; 358 } 359 } 360 361 private static class SinkHolder { 362 static volatile Object sink; 363 364 // Ensure that sink looks live to even a reasonably clever compiler. 365 private static volatile int finalize_count = 0; 366 367 private static Object sinkUser = new Object() { 368 protected void finalize() { 369 if (sink == null && finalize_count > 0) { 370 throw new AssertionError("Can't get here"); 371 } 372 finalize_count++; 373 } 374 }; 375 } 376 // END Android-added: reachabilityFence() from upstream OpenJDK9+181. 377 } 378