1 /*
2 * Copyright (c) 1997, 2018, 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.ForceInline;
29 import jdk.internal.HotSpotIntrinsicCandidate;
30 import jdk.internal.misc.JavaLangRefAccess;
31 import jdk.internal.misc.SharedSecrets;
32 import jdk.internal.ref.Cleaner;
33
34 /**
35 * Abstract base class for reference objects. This class defines the
36 * operations common to all reference objects. Because reference objects are
37 * implemented in close cooperation with the garbage collector, this class may
38 * not be subclassed directly.
39 *
40 * @author Mark Reinhold
41 * @since 1.2
42 */
43
44 public abstract class Reference<T> {
45
46 /* The state of a Reference object is characterized by two attributes. It
47 * may be either "active", "pending", or "inactive". It may also be
48 * either "registered", "enqueued", "dequeued", or "unregistered".
49 *
50 * Active: Subject to special treatment by the garbage collector. Some
51 * time after the collector detects that the reachability of the
52 * referent has changed to the appropriate state, the collector
53 * "notifies" the reference, changing the state to either "pending" or
54 * "inactive".
55 * referent != null; discovered = null, or in GC discovered list.
56 *
57 * Pending: An element of the pending-Reference list, waiting to be
58 * processed by the ReferenceHandler thread. The pending-Reference
59 * list is linked through the discovered fields of references in the
60 * list.
61 * referent = null; discovered = next element in pending-Reference list.
62 *
63 * Inactive: Neither Active nor Pending.
64 * referent = null.
65 *
66 * Registered: Associated with a queue when created, and not yet added
67 * to the queue.
68 * queue = the associated queue.
69 *
70 * Enqueued: Added to the associated queue, and not yet removed.
71 * queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to
72 * indicate end of list.
73 *
74 * Dequeued: Added to the associated queue and then removed.
75 * queue = ReferenceQueue.NULL; next = this.
76 *
77 * Unregistered: Not associated with a queue when created.
78 * queue = ReferenceQueue.NULL.
79 *
80 * The collector only needs to examine the referent field and the
81 * discovered field to determine whether a (non-FinalReference) Reference
82 * object needs special treatment. If the referent is non-null and not
83 * known to be live, then it may need to be discovered for possible later
84 * notification. But if the discovered field is non-null, then it has
85 * already been discovered.
86 *
87 * FinalReference (which exists to support finalization) differs from
88 * other references, because a FinalReference is not cleared when
89 * notified. The referent being null or not cannot be used to distinguish
90 * between the active state and pending or inactive states. However,
91 * FinalReferences do not support enqueue(). Instead, the next field of a
92 * FinalReference object is set to "this" when it is added to the
93 * pending-Reference list. The use of "this" as the value of next in the
94 * enqueued and dequeued states maintains the non-active state. An
95 * additional check that the next field is null is required to determine
96 * that a FinalReference object is active.
97 *
98 * Initial states:
99 * [active/registered]
100 * [active/unregistered] [1]
101 *
102 * Transitions:
103 * clear
104 * [active/registered] -------> [inactive/registered]
105 * | |
106 * | | enqueue [2]
107 * | GC enqueue [2] |
108 * | -----------------|
109 * | |
110 * v |
111 * [pending/registered] --- v
112 * | | ReferenceHandler
113 * | enqueue [2] |---> [inactive/enqueued]
114 * v | |
115 * [pending/enqueued] --- |
116 * | | poll/remove
117 * | poll/remove |
118 * | |
119 * v ReferenceHandler v
120 * [pending/dequeued] ------> [inactive/dequeued]
121 *
122 *
123 * clear/enqueue/GC [3]
124 * [active/unregistered] ------
125 * | |
126 * | GC |
127 * | |--> [inactive/unregistered]
128 * v |
129 * [pending/unregistered] ------
130 * ReferenceHandler
131 *
132 * Terminal states:
133 * [inactive/dequeued]
134 * [inactive/unregistered]
135 *
136 * Unreachable states (because enqueue also clears):
137 * [active/enqeued]
138 * [active/dequeued]
139 *
140 * [1] Unregistered is not permitted for FinalReferences.
141 *
142 * [2] These transitions are not possible for FinalReferences, making
143 * [pending/enqueued] and [pending/dequeued] unreachable, and
144 * [inactive/registered] terminal.
145 *
146 * [3] The garbage collector may directly transition a Reference
147 * from [active/unregistered] to [inactive/unregistered],
148 * bypassing the pending-Reference list.
149 */
150
151 private T referent; /* Treated specially by GC */
152
153 /* The queue this reference gets enqueued to by GC notification or by
154 * calling enqueue().
155 *
156 * When registered: the queue with which this reference is registered.
157 * enqueued: ReferenceQueue.ENQUEUE
158 * dequeued: ReferenceQueue.NULL
159 * unregistered: ReferenceQueue.NULL
160 */
161 volatile ReferenceQueue<? super T> queue;
162
163 /* The link in a ReferenceQueue's list of Reference objects.
164 *
165 * When registered: null
166 * enqueued: next element in queue (or this if last)
167 * dequeued: this (marking FinalReferences as inactive)
168 * unregistered: null
169 */
170 @SuppressWarnings("rawtypes")
171 volatile Reference next;
172
173 /* Used by the garbage collector to accumulate Reference objects that need
174 * to be revisited in order to decide whether they should be notified.
175 * Also used as the link in the pending-Reference list. The discovered
176 * field and the next field are distinct to allow the enqueue() method to
177 * be applied to a Reference object while it is either in the
178 * pending-Reference list or in the garbage collector's discovered set.
179 *
180 * When active: null or next element in a discovered reference list
181 * maintained by the GC (or this if last)
182 * pending: next element in the pending-Reference list (null if last)
183 * inactive: null
184 */
185 private transient Reference<T> discovered;
186
187
188 /* High-priority thread to enqueue pending References
189 */
190 private static class ReferenceHandler extends Thread {
191
192 private static void ensureClassInitialized(Class<?> clazz) {
193 try {
194 Class.forName(clazz.getName(), true, clazz.getClassLoader());
195 } catch (ClassNotFoundException e) {
196 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
197 }
198 }
199
200 static {
201 // pre-load and initialize Cleaner class so that we don't
202 // get into trouble later in the run loop if there's
203 // memory shortage while loading/initializing it lazily.
204 ensureClassInitialized(Cleaner.class);
205 }
206
207 ReferenceHandler(ThreadGroup g, String name) {
208 super(g, null, name, 0, false);
209 }
210
211 public void run() {
212 while (true) {
213 processPendingReferences();
214 }
215 }
216 }
217
218 /*
219 * Atomically get and clear (set to null) the VM's pending-Reference list.
220 */
221 private static native Reference<Object> getAndClearReferencePendingList();
222
223 /*
224 * Test whether the VM's pending-Reference list contains any entries.
225 */
226 private static native boolean hasReferencePendingList();
227
228 /*
229 * Wait until the VM's pending-Reference list may be non-null.
230 */
231 private static native void waitForReferencePendingList();
232
233 private static final Object processPendingLock = new Object();
234 private static boolean processPendingActive = false;
235
236 private static void processPendingReferences() {
237 // Only the singleton reference processing thread calls
238 // waitForReferencePendingList() and getAndClearReferencePendingList().
239 // These are separate operations to avoid a race with other threads
240 // that are calling waitForReferenceProcessing().
241 waitForReferencePendingList();
242 Reference<Object> pendingList;
243 synchronized (processPendingLock) {
244 pendingList = getAndClearReferencePendingList();
245 processPendingActive = true;
246 }
247 while (pendingList != null) {
248 Reference<Object> ref = pendingList;
249 pendingList = ref.discovered;
250 ref.discovered = null;
251
252 if (ref instanceof Cleaner) {
253 ((Cleaner)ref).clean();
254 // Notify any waiters that progress has been made.
255 // This improves latency for nio.Bits waiters, which
256 // are the only important ones.
257 synchronized (processPendingLock) {
258 processPendingLock.notifyAll();
259 }
260 } else {
261 ReferenceQueue<? super Object> q = ref.queue;
262 if (q != ReferenceQueue.NULL) q.enqueue(ref);
263 }
264 }
265 // Notify any waiters of completion of current round.
266 synchronized (processPendingLock) {
267 processPendingActive = false;
268 processPendingLock.notifyAll();
269 }
270 }
271
272 // Wait for progress in reference processing.
273 //
274 // Returns true after waiting (for notification from the reference
275 // processing thread) if either (1) the VM has any pending
276 // references, or (2) the reference processing thread is
277 // processing references. Otherwise, returns false immediately.
278 private static boolean waitForReferenceProcessing()
279 throws InterruptedException
280 {
281 synchronized (processPendingLock) {
282 if (processPendingActive || hasReferencePendingList()) {
283 // Wait for progress, not necessarily completion.
284 processPendingLock.wait();
285 return true;
286 } else {
287 return false;
288 }
289 }
290 }
291
292 static {
293 ThreadGroup tg = Thread.currentThread().getThreadGroup();
294 for (ThreadGroup tgn = tg;
295 tgn != null;
296 tg = tgn, tgn = tg.getParent());
297 Thread handler = new ReferenceHandler(tg, "Reference Handler");
298 /* If there were a special system-only priority greater than
299 * MAX_PRIORITY, it would be used here
300 */
301 handler.setPriority(Thread.MAX_PRIORITY);
302 handler.setDaemon(true);
303 handler.start();
304
305 // provide access in SharedSecrets
306 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
307 @Override
308 public boolean waitForReferenceProcessing()
309 throws InterruptedException
310 {
311 return Reference.waitForReferenceProcessing();
312 }
313
314 @Override
315 public void runFinalization() {
316 Finalizer.runFinalization();
317 }
318 });
319 }
320
321 /* -- Referent accessor and setters -- */
322
323 /**
324 * Returns this reference object's referent. If this reference object has
325 * been cleared, either by the program or by the garbage collector, then
326 * this method returns <code>null</code>.
327 *
328 * @return The object to which this reference refers, or
329 * <code>null</code> if this reference object has been cleared
330 */
331 @HotSpotIntrinsicCandidate
332 public T get() {
333 return this.referent;
334 }
335
336 /**
337 * Clears this reference object. Invoking this method will not cause this
338 * object to be enqueued.
339 *
340 * <p> This method is invoked only by Java code; when the garbage collector
341 * clears references it does so directly, without invoking this method.
342 */
343 public void clear() {
344 this.referent = null;
345 }
346
347 /* -- Queue operations -- */
348
349 /**
350 * Tells whether or not this reference object has been enqueued, either by
351 * the program or by the garbage collector. If this reference object was
352 * not registered with a queue when it was created, then this method will
353 * always return <code>false</code>.
354 *
355 * @return <code>true</code> if and only if this reference object has
356 * been enqueued
357 */
358 public boolean isEnqueued() {
359 return (this.queue == ReferenceQueue.ENQUEUED);
360 }
361
362 /**
363 * Clears this reference object and adds it to the queue with which
364 * it is registered, if any.
365 *
366 * <p> This method is invoked only by Java code; when the garbage collector
367 * enqueues references it does so directly, without invoking this method.
368 *
369 * @return <code>true</code> if this reference object was successfully
370 * enqueued; <code>false</code> if it was already enqueued or if
371 * it was not registered with a queue when it was created
372 */
373 public boolean enqueue() {
374 this.referent = null;
375 return this.queue.enqueue(this);
376 }
377
378 /**
379 * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be
380 * meaningfully cloned. Construct a new {@code Reference} instead.
381 *
382 * @returns never returns normally
383 * @throws CloneNotSupportedException always
384 *
385 * @since 11
386 */
387 @Override
388 protected Object clone() throws CloneNotSupportedException {
389 throw new CloneNotSupportedException();
390 }
391
392 /* -- Constructors -- */
393
394 Reference(T referent) {
395 this(referent, null);
396 }
397
398 Reference(T referent, ReferenceQueue<? super T> queue) {
399 this.referent = referent;
400 this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
401 }
402
403 /**
404 * Ensures that the object referenced by the given reference remains
405 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
406 * regardless of any prior actions of the program that might otherwise cause
407 * the object to become unreachable; thus, the referenced object is not
408 * reclaimable by garbage collection at least until after the invocation of
409 * this method. Invocation of this method does not itself initiate garbage
410 * collection or finalization.
411 *
412 * <p> This method establishes an ordering for
413 * <a href="package-summary.html#reachability"><em>strong reachability</em></a>
414 * with respect to garbage collection. It controls relations that are
415 * otherwise only implicit in a program -- the reachability conditions
416 * triggering garbage collection. This method is designed for use in
417 * uncommon situations of premature finalization where using
418 * {@code synchronized} blocks or methods, or using other synchronization
419 * facilities are not possible or do not provide the desired control. This
420 * method is applicable only when reclamation may have visible effects,
421 * which is possible for objects with finalizers (See
422 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6">
423 * Section 12.6 17 of <cite>The Java™ Language Specification</cite></a>)
424 * that are implemented in ways that rely on ordering control for correctness.
425 *
426 * @apiNote
427 * Finalization may occur whenever the virtual machine detects that no
428 * reference to an object will ever be stored in the heap: The garbage
429 * collector may reclaim an object even if the fields of that object are
430 * still in use, so long as the object has otherwise become unreachable.
431 * This may have surprising and undesirable effects in cases such as the
432 * following example in which the bookkeeping associated with a class is
433 * managed through array indices. Here, method {@code action} uses a
434 * {@code reachabilityFence} to ensure that the {@code Resource} object is
435 * not reclaimed before bookkeeping on an associated
436 * {@code ExternalResource} has been performed; in particular here, to
437 * ensure that the array slot holding the {@code ExternalResource} is not
438 * nulled out in method {@link Object#finalize}, which may otherwise run
439 * concurrently.
440 *
441 * <pre> {@code
442 * class Resource {
443 * private static ExternalResource[] externalResourceArray = ...
444 *
445 * int myIndex;
446 * Resource(...) {
447 * myIndex = ...
448 * externalResourceArray[myIndex] = ...;
449 * ...
450 * }
451 * protected void finalize() {
452 * externalResourceArray[myIndex] = null;
453 * ...
454 * }
455 * public void action() {
456 * try {
457 * // ...
458 * int i = myIndex;
459 * Resource.update(externalResourceArray[i]);
460 * } finally {
461 * Reference.reachabilityFence(this);
462 * }
463 * }
464 * private static void update(ExternalResource ext) {
465 * ext.status = ...;
466 * }
467 * }}</pre>
468 *
469 * Here, the invocation of {@code reachabilityFence} is nonintuitively
470 * placed <em>after</em> the call to {@code update}, to ensure that the
471 * array slot is not nulled out by {@link Object#finalize} before the
472 * update, even if the call to {@code action} was the last use of this
473 * object. This might be the case if, for example a usage in a user program
474 * had the form {@code new Resource().action();} which retains no other
475 * reference to this {@code Resource}. While probably overkill here,
476 * {@code reachabilityFence} is placed in a {@code finally} block to ensure
477 * that it is invoked across all paths in the method. In a method with more
478 * complex control paths, you might need further precautions to ensure that
479 * {@code reachabilityFence} is encountered along all of them.
480 *
481 * <p> It is sometimes possible to better encapsulate use of
482 * {@code reachabilityFence}. Continuing the above example, if it were
483 * acceptable for the call to method {@code update} to proceed even if the
484 * finalizer had already executed (nulling out slot), then you could
485 * localize use of {@code reachabilityFence}:
486 *
487 * <pre> {@code
488 * public void action2() {
489 * // ...
490 * Resource.update(getExternalResource());
491 * }
492 * private ExternalResource getExternalResource() {
493 * ExternalResource ext = externalResourceArray[myIndex];
494 * Reference.reachabilityFence(this);
495 * return ext;
496 * }}</pre>
497 *
498 * <p> Method {@code reachabilityFence} is not required in constructions
499 * that themselves ensure reachability. For example, because objects that
500 * are locked cannot, in general, be reclaimed, it would suffice if all
501 * accesses of the object, in all methods of class {@code Resource}
502 * (including {@code finalize}) were enclosed in {@code synchronized (this)}
503 * blocks. (Further, such blocks must not include infinite loops, or
504 * themselves be unreachable, which fall into the corner case exceptions to
505 * the "in general" disclaimer.) However, method {@code reachabilityFence}
506 * remains a better option in cases where this approach is not as efficient,
507 * desirable, or possible; for example because it would encounter deadlock.
508 *
509 * @param ref the reference. If {@code null}, this method has no effect.
510 * @since 9
511 */
512 @ForceInline
513 public static void reachabilityFence(Object ref) {
514 // Does nothing. This method is annotated with @ForceInline to eliminate
515 // most of the overhead that using @DontInline would cause with the
516 // HotSpot JVM, when this fence is used in a wide variety of situations.
517 // HotSpot JVM retains the ref and does not GC it before a call to
518 // this method, because the JIT-compilers do not have GC-only safepoints.
519 }
520 }
521