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