• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::LinkFields() knows this is the
67     // 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     /* -- Constructors -- */
208 
Reference(T referent)209     Reference(T referent) {
210         this(referent, null);
211     }
212 
Reference(T referent, ReferenceQueue<? super T> queue)213     Reference(T referent, ReferenceQueue<? super T> queue) {
214         this.referent = referent;
215         this.queue = queue;
216     }
217     // END Android-changed: Reimplemented to accommodate a different GC and compiler.
218 
219     // BEGIN Android-added: reachabilityFence() from upstream OpenJDK9+181.
220     // The actual implementation differs from OpenJDK9.
221     /**
222      * Ensures that the object referenced by the given reference remains
223      * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
224      * regardless of any prior actions of the program that might otherwise cause
225      * the object to become unreachable; thus, the referenced object is not
226      * reclaimable by garbage collection at least until after the invocation of
227      * this method.  Invocation of this method does not itself initiate garbage
228      * collection or finalization.
229      *
230      * <p> This method establishes an ordering for
231      * <a href="package-summary.html#reachability"><em>strong reachability</em></a>
232      * with respect to garbage collection.  It controls relations that are
233      * otherwise only implicit in a program -- the reachability conditions
234      * triggering garbage collection.  This method is designed for use in
235      * uncommon situations of premature finalization where using
236      * {@code synchronized} blocks or methods, or using other synchronization
237      * facilities are not possible or do not provide the desired control.  This
238      * method is applicable only when reclamation may have visible effects,
239      * which is possible for objects with finalizers (See
240      * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6">
241      * Section 12.6 17 of <cite>The Java&trade; Language Specification</cite></a>)
242      * that are implemented in ways that rely on ordering control for correctness.
243      *
244      * @apiNote
245      * Finalization may occur whenever the virtual machine detects that no
246      * reference to an object will ever be stored in the heap: The garbage
247      * collector may reclaim an object even if the fields of that object are
248      * still in use, so long as the object has otherwise become unreachable.
249      * This may have surprising and undesirable effects in cases such as the
250      * following example in which the bookkeeping associated with a class is
251      * managed through array indices.  Here, method {@code action} uses a
252      * {@code reachabilityFence} to ensure that the {@code Resource} object is
253      * not reclaimed before bookkeeping on an associated
254      * {@code ExternalResource} has been performed; in particular here, to
255      * ensure that the array slot holding the {@code ExternalResource} is not
256      * nulled out in method {@link Object#finalize}, which may otherwise run
257      * concurrently.
258      *
259      * <pre> {@code
260      * class Resource {
261      *   private static ExternalResource[] externalResourceArray = ...
262      *
263      *   int myIndex;
264      *   Resource(...) {
265      *     myIndex = ...
266      *     externalResourceArray[myIndex] = ...;
267      *     ...
268      *   }
269      *   protected void finalize() {
270      *     externalResourceArray[myIndex] = null;
271      *     ...
272      *   }
273      *   public void action() {
274      *     try {
275      *       // ...
276      *       int i = myIndex;
277      *       Resource.update(externalResourceArray[i]);
278      *     } finally {
279      *       Reference.reachabilityFence(this);
280      *     }
281      *   }
282      *   private static void update(ExternalResource ext) {
283      *     ext.status = ...;
284      *   }
285      * }}</pre>
286      *
287      * Here, the invocation of {@code reachabilityFence} is nonintuitively
288      * placed <em>after</em> the call to {@code update}, to ensure that the
289      * array slot is not nulled out by {@link Object#finalize} before the
290      * update, even if the call to {@code action} was the last use of this
291      * object.  This might be the case if, for example a usage in a user program
292      * had the form {@code new Resource().action();} which retains no other
293      * reference to this {@code Resource}.  While probably overkill here,
294      * {@code reachabilityFence} is placed in a {@code finally} block to ensure
295      * that it is invoked across all paths in the method.  In a method with more
296      * complex control paths, you might need further precautions to ensure that
297      * {@code reachabilityFence} is encountered along all of them.
298      *
299      * <p> It is sometimes possible to better encapsulate use of
300      * {@code reachabilityFence}.  Continuing the above example, if it were
301      * acceptable for the call to method {@code update} to proceed even if the
302      * finalizer had already executed (nulling out slot), then you could
303      * localize use of {@code reachabilityFence}:
304      *
305      * <pre> {@code
306      * public void action2() {
307      *   // ...
308      *   Resource.update(getExternalResource());
309      * }
310      * private ExternalResource getExternalResource() {
311      *   ExternalResource ext = externalResourceArray[myIndex];
312      *   Reference.reachabilityFence(this);
313      *   return ext;
314      * }}</pre>
315      *
316      * <p> Method {@code reachabilityFence} is not required in constructions
317      * that themselves ensure reachability.  For example, because objects that
318      * are locked cannot, in general, be reclaimed, it would suffice if all
319      * accesses of the object, in all methods of class {@code Resource}
320      * (including {@code finalize}) were enclosed in {@code synchronized (this)}
321      * blocks.  (Further, such blocks must not include infinite loops, or
322      * themselves be unreachable, which fall into the corner case exceptions to
323      * the "in general" disclaimer.)  However, method {@code reachabilityFence}
324      * remains a better option in cases where this approach is not as efficient,
325      * desirable, or possible; for example because it would encounter deadlock.
326      *
327      * @param ref the reference. If {@code null}, this method has no effect.
328      * @since 9
329      */
330     // @DontInline
reachabilityFence(Object ref)331     public static void reachabilityFence(Object ref) {
332         // This code is usually replaced by much faster intrinsic implementations.
333         // It will be executed for tests run with the access checks interpreter in
334         // ART, e.g. with --verify-soft-fail.  Since this is a volatile store, it
335         // cannot easily be moved up past prior accesses, even if this method is
336         // inlined.
337         SinkHolder.sink = ref;
338         // Leaving SinkHolder set to ref is unpleasant, since it keeps ref live
339         // until the next reachabilityFence call. This causes e.g. 036-finalizer
340         // to fail. Clear it again in a way that's unlikely to be optimizable.
341         // The fact that finalize_count is volatile makes it hard to move the test up.
342         if (SinkHolder.finalize_count == 0) {
343             SinkHolder.sink = null;
344         }
345     }
346 
347     private static class SinkHolder {
348         static volatile Object sink;
349 
350         // Ensure that sink looks live to even a reasonably clever compiler.
351         private static volatile int finalize_count = 0;
352 
353         private static Object sinkUser = new Object() {
354             protected void finalize() {
355                 if (sink == null && finalize_count > 0) {
356                     throw new AssertionError("Can't get here");
357                 }
358                 finalize_count++;
359             }
360         };
361     }
362     // END Android-added: reachabilityFence() from upstream OpenJDK9+181.
363 }
364