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 // BEGIN Android-changed: Reimplemented to accommodate a different GC and compiler. 42 // ClassLinker knows about the fields of this class. 43 44 public abstract class Reference<T> { 45 /** 46 * Forces JNI path. 47 * If GC is not in progress (ie: not going through slow path), the referent 48 * can be quickly returned through intrinsic without passing through JNI. 49 * This flag forces the JNI path so that it can be tested and benchmarked. 50 */ 51 private static boolean disableIntrinsic = false; 52 53 /** 54 * Slow path flag for the reference processor. 55 * Used by the reference processor to determine whether or not the referent 56 * can be immediately returned. Because the referent might get swept during 57 * GC, the slow path, which passes through JNI, must be taken. 58 */ 59 private static boolean slowPathEnabled = false; 60 61 // Treated specially by GC. ART's ClassLinker::LinkFields() knows this is the 62 // alphabetically last non-static field. 63 volatile T referent; 64 65 final ReferenceQueue<? super T> queue; 66 67 /* 68 * This field forms a singly-linked list of reference objects that have 69 * been enqueued. The queueNext field is non-null if and only if this 70 * reference has been enqueued. After this reference has been enqueued and 71 * before it has been removed from its queue, the queueNext field points 72 * to the next reference on the queue. The last reference on a queue 73 * points to itself. Once this reference has been removed from the 74 * reference queue, the queueNext field points to the 75 * ReferenceQueue.sQueueNextUnenqueued sentinel reference object for the 76 * rest of this reference's lifetime. 77 * <p> 78 * Access to the queueNext field is guarded by synchronization on a lock 79 * internal to 'queue'. 80 */ 81 Reference queueNext; 82 83 /** 84 * The pendingNext field is initially set by the GC. After the GC forms a 85 * complete circularly linked list, the list is handed off to the 86 * ReferenceQueueDaemon using the ReferenceQueue.class lock. The 87 * ReferenceQueueDaemon can then read the pendingNext fields without 88 * additional synchronization. 89 */ 90 Reference<?> pendingNext; 91 92 /* -- Referent accessor and setters -- */ 93 94 /** 95 * Returns this reference object's referent. If this reference object has 96 * been cleared, either by the program or by the garbage collector, then 97 * this method returns <code>null</code>. 98 * 99 * @return The object to which this reference refers, or 100 * <code>null</code> if this reference object has been cleared 101 */ get()102 public T get() { 103 return getReferent(); 104 } 105 106 @FastNative getReferent()107 private final native T getReferent(); 108 109 /** 110 * Clears this reference object. Invoking this method will not cause this 111 * object to be enqueued. 112 * 113 * <p> This method is invoked only by Java code; when the garbage collector 114 * clears references it does so directly, without invoking this method. 115 */ clear()116 public void clear() { 117 clearReferent(); 118 } 119 120 // Direct access to the referent is prohibited, clearReferent blocks and set 121 // the referent to null when it is safe to do so. 122 @FastNative clearReferent()123 native void clearReferent(); 124 125 /* -- Queue operations -- */ 126 127 /** 128 * Tells whether or not this reference object has been enqueued, either by 129 * the program or by the garbage collector. If this reference object was 130 * not registered with a queue when it was created, then this method will 131 * always return <code>false</code>. 132 * 133 * @return <code>true</code> if and only if this reference object has 134 * been enqueued 135 */ isEnqueued()136 public boolean isEnqueued() { 137 // Contrary to what the documentation says, this method returns false 138 // after this reference object has been removed from its queue 139 // (b/26647823). ReferenceQueue.isEnqueued preserves this historically 140 // incorrect behavior. 141 return queue != null && queue.isEnqueued(this); 142 } 143 144 /** 145 * Adds this reference object to the queue with which it is registered, 146 * if any. 147 * 148 * <p> This method is invoked only by Java code; when the garbage collector 149 * enqueues references it does so directly, without invoking this method. 150 * 151 * @return <code>true</code> if this reference object was successfully 152 * enqueued; <code>false</code> if it was already enqueued or if 153 * it was not registered with a queue when it was created 154 */ enqueue()155 public boolean enqueue() { 156 return queue != null && queue.enqueue(this); 157 } 158 159 /* -- Constructors -- */ 160 Reference(T referent)161 Reference(T referent) { 162 this(referent, null); 163 } 164 Reference(T referent, ReferenceQueue<? super T> queue)165 Reference(T referent, ReferenceQueue<? super T> queue) { 166 this.referent = referent; 167 this.queue = queue; 168 } 169 // END Android-changed: Reimplemented to accommodate a different GC and compiler. 170 171 // BEGIN Android-added: reachabilityFence() from upstream OpenJDK9+181. 172 // The actual implementation differs from OpenJDK9. 173 /** 174 * Ensures that the object referenced by the given reference remains 175 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>, 176 * regardless of any prior actions of the program that might otherwise cause 177 * the object to become unreachable; thus, the referenced object is not 178 * reclaimable by garbage collection at least until after the invocation of 179 * this method. Invocation of this method does not itself initiate garbage 180 * collection or finalization. 181 * 182 * <p> This method establishes an ordering for 183 * <a href="package-summary.html#reachability"><em>strong reachability</em></a> 184 * with respect to garbage collection. It controls relations that are 185 * otherwise only implicit in a program -- the reachability conditions 186 * triggering garbage collection. This method is designed for use in 187 * uncommon situations of premature finalization where using 188 * {@code synchronized} blocks or methods, or using other synchronization 189 * facilities are not possible or do not provide the desired control. This 190 * method is applicable only when reclamation may have visible effects, 191 * which is possible for objects with finalizers (See 192 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6"> 193 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>) 194 * that are implemented in ways that rely on ordering control for correctness. 195 * 196 * @apiNote 197 * Finalization may occur whenever the virtual machine detects that no 198 * reference to an object will ever be stored in the heap: The garbage 199 * collector may reclaim an object even if the fields of that object are 200 * still in use, so long as the object has otherwise become unreachable. 201 * This may have surprising and undesirable effects in cases such as the 202 * following example in which the bookkeeping associated with a class is 203 * managed through array indices. Here, method {@code action} uses a 204 * {@code reachabilityFence} to ensure that the {@code Resource} object is 205 * not reclaimed before bookkeeping on an associated 206 * {@code ExternalResource} has been performed; in particular here, to 207 * ensure that the array slot holding the {@code ExternalResource} is not 208 * nulled out in method {@link Object#finalize}, which may otherwise run 209 * concurrently. 210 * 211 * <pre> {@code 212 * class Resource { 213 * private static ExternalResource[] externalResourceArray = ... 214 * 215 * int myIndex; 216 * Resource(...) { 217 * myIndex = ... 218 * externalResourceArray[myIndex] = ...; 219 * ... 220 * } 221 * protected void finalize() { 222 * externalResourceArray[myIndex] = null; 223 * ... 224 * } 225 * public void action() { 226 * try { 227 * // ... 228 * int i = myIndex; 229 * Resource.update(externalResourceArray[i]); 230 * } finally { 231 * Reference.reachabilityFence(this); 232 * } 233 * } 234 * private static void update(ExternalResource ext) { 235 * ext.status = ...; 236 * } 237 * }}</pre> 238 * 239 * Here, the invocation of {@code reachabilityFence} is nonintuitively 240 * placed <em>after</em> the call to {@code update}, to ensure that the 241 * array slot is not nulled out by {@link Object#finalize} before the 242 * update, even if the call to {@code action} was the last use of this 243 * object. This might be the case if, for example a usage in a user program 244 * had the form {@code new Resource().action();} which retains no other 245 * reference to this {@code Resource}. While probably overkill here, 246 * {@code reachabilityFence} is placed in a {@code finally} block to ensure 247 * that it is invoked across all paths in the method. In a method with more 248 * complex control paths, you might need further precautions to ensure that 249 * {@code reachabilityFence} is encountered along all of them. 250 * 251 * <p> It is sometimes possible to better encapsulate use of 252 * {@code reachabilityFence}. Continuing the above example, if it were 253 * acceptable for the call to method {@code update} to proceed even if the 254 * finalizer had already executed (nulling out slot), then you could 255 * localize use of {@code reachabilityFence}: 256 * 257 * <pre> {@code 258 * public void action2() { 259 * // ... 260 * Resource.update(getExternalResource()); 261 * } 262 * private ExternalResource getExternalResource() { 263 * ExternalResource ext = externalResourceArray[myIndex]; 264 * Reference.reachabilityFence(this); 265 * return ext; 266 * }}</pre> 267 * 268 * <p> Method {@code reachabilityFence} is not required in constructions 269 * that themselves ensure reachability. For example, because objects that 270 * are locked cannot, in general, be reclaimed, it would suffice if all 271 * accesses of the object, in all methods of class {@code Resource} 272 * (including {@code finalize}) were enclosed in {@code synchronized (this)} 273 * blocks. (Further, such blocks must not include infinite loops, or 274 * themselves be unreachable, which fall into the corner case exceptions to 275 * the "in general" disclaimer.) However, method {@code reachabilityFence} 276 * remains a better option in cases where this approach is not as efficient, 277 * desirable, or possible; for example because it would encounter deadlock. 278 * 279 * @param ref the reference. If {@code null}, this method has no effect. 280 * @since 9 281 */ 282 // @DontInline reachabilityFence(Object ref)283 public static void reachabilityFence(Object ref) { 284 // This code is usually replaced by much faster intrinsic implementations. 285 // It will be executed for tests run with the access checks interpreter in 286 // ART, e.g. with --verify-soft-fail. Since this is a volatile store, it 287 // cannot easily be moved up past prior accesses, even if this method is 288 // inlined. 289 SinkHolder.sink = ref; 290 // Leaving SinkHolder set to ref is unpleasant, since it keeps ref live 291 // until the next reachabilityFence call. This causes e.g. 036-finalizer 292 // to fail. Clear it again in a way that's unlikely to be optimizable. 293 // The fact that finalize_count is volatile makes it hard to move the test up. 294 if (SinkHolder.finalize_count == 0) { 295 SinkHolder.sink = null; 296 } 297 } 298 299 private static class SinkHolder { 300 static volatile Object sink; 301 302 // Ensure that sink looks live to even a reasonably clever compiler. 303 private static volatile int finalize_count = 0; 304 305 private static Object sinkUser = new Object() { 306 protected void finalize() { 307 if (sink == null && finalize_count > 0) { 308 throw new AssertionError("Can't get here"); 309 } 310 finalize_count++; 311 } 312 }; 313 } 314 // END Android-added: reachabilityFence() from upstream OpenJDK9+181. 315 } 316