1 /*
2 * Copyright (c) 1997, 2025, 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.AOTRuntimeSetup;
29 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
30 import jdk.internal.vm.annotation.ForceInline;
31 import jdk.internal.vm.annotation.IntrinsicCandidate;
32 import jdk.internal.access.JavaLangRefAccess;
33 import jdk.internal.access.SharedSecrets;
34
35 /**
36 * Abstract base class for reference objects. This class defines the
37 * operations common to all reference objects. Because reference objects are
38 * implemented in close cooperation with the garbage collector, this class may
39 * not be subclassed directly.
40 * @param <T> the type of the referent
41 *
42 * @author Mark Reinhold
43 * @since 1.2
44 * @sealedGraph
45 */
46 @AOTSafeClassInitializer
47 public abstract sealed class Reference<@jdk.internal.RequiresIdentity T>
48 permits PhantomReference, SoftReference, WeakReference, FinalReference {
49
50 /* The state of a Reference object is characterized by two attributes. It
51 * may be either "active", "pending", or "inactive". It may also be
52 * either "registered", "enqueued", "dequeued", or "unregistered".
53 *
54 * Active: Subject to special treatment by the garbage collector. Some
55 * time after the collector detects that the reachability of the
56 * referent has changed to the appropriate state, the collector
57 * "notifies" the reference, changing the state to either "pending" or
58 * "inactive".
59 * referent != null; discovered = null, or in GC discovered list.
60 *
61 * Pending: An element of the pending-Reference list, waiting to be
62 * processed by the ReferenceHandler thread. The pending-Reference
63 * list is linked through the discovered fields of references in the
64 * list.
65 * referent = null; discovered = next element in pending-Reference list.
66 *
67 * Inactive: Neither Active nor Pending.
68 * referent = null.
69 *
70 * Registered: Associated with a queue when created, and not yet added
71 * to the queue.
72 * queue = the associated queue.
73 *
74 * Enqueued: Added to the associated queue, and not yet removed.
75 * queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to
76 * indicate end of list.
77 *
78 * Dequeued: Added to the associated queue and then removed.
79 * queue = ReferenceQueue.NULL_QUEUE; next = this.
80 *
81 * Unregistered: Not associated with a queue when created.
82 * queue = ReferenceQueue.NULL_QUEUE.
83 *
84 * The collector only needs to examine the referent field and the
85 * discovered field to determine whether a (non-FinalReference) Reference
86 * object needs special treatment. If the referent is non-null and not
87 * known to be live, then it may need to be discovered for possible later
88 * notification. But if the discovered field is non-null, then it has
89 * already been discovered.
90 *
91 * FinalReference (which exists to support finalization) differs from
92 * other references, because a FinalReference is not cleared when
93 * notified. The referent being null or not cannot be used to distinguish
94 * between the active state and pending or inactive states. However,
95 * FinalReferences do not support enqueue(). Instead, the next field of a
96 * FinalReference object is set to "this" when it is added to the
97 * pending-Reference list. The use of "this" as the value of next in the
98 * enqueued and dequeued states maintains the non-active state. An
99 * additional check that the next field is null is required to determine
100 * that a FinalReference object is active.
101 *
102 * Initial states:
103 * [active/registered]
104 * [active/unregistered] [1]
105 *
106 * Transitions:
107 * clear [2]
108 * [active/registered] -------> [inactive/registered]
109 * | |
110 * | | enqueue
111 * | GC enqueue [2] |
112 * | -----------------|
113 * | |
114 * v |
115 * [pending/registered] --- v
116 * | | ReferenceHandler
117 * | enqueue [2] |---> [inactive/enqueued]
118 * v | |
119 * [pending/enqueued] --- |
120 * | | poll/remove
121 * | poll/remove | + clear [4]
122 * | |
123 * v ReferenceHandler v
124 * [pending/dequeued] ------> [inactive/dequeued]
125 *
126 *
127 * clear/enqueue/GC [3]
128 * [active/unregistered] ------
129 * | |
130 * | GC |
131 * | |--> [inactive/unregistered]
132 * v |
133 * [pending/unregistered] ------
134 * ReferenceHandler
135 *
136 * Terminal states:
137 * [inactive/dequeued]
138 * [inactive/unregistered]
139 *
140 * Unreachable states (because enqueue also clears):
141 * [active/enqueued]
142 * [active/dequeued]
143 *
144 * [1] Unregistered is not permitted for FinalReferences.
145 *
146 * [2] These transitions are not possible for FinalReferences, making
147 * [pending/enqueued], [pending/dequeued], and [inactive/registered]
148 * unreachable.
149 *
150 * [3] The garbage collector may directly transition a Reference
151 * from [active/unregistered] to [inactive/unregistered],
152 * bypassing the pending-Reference list.
153 *
154 * [4] The queue handler for FinalReferences also clears the reference.
155 */
156
157 private T referent; /* Treated specially by GC */
158
159 /* The queue this reference gets enqueued to by GC notification or by
160 * calling enqueue().
161 *
162 * When registered: the queue with which this reference is registered.
163 * enqueued: ReferenceQueue.ENQUEUE
164 * dequeued: ReferenceQueue.NULL_QUEUE
165 * unregistered: ReferenceQueue.NULL_QUEUE
166 */
167 volatile ReferenceQueue<? super T> queue;
168
169 /* The link in a ReferenceQueue's list of Reference objects.
170 *
171 * When registered: null
172 * enqueued: next element in queue (or this if last)
173 * dequeued: this (marking FinalReferences as inactive)
174 * unregistered: null
175 */
176 @SuppressWarnings("rawtypes")
177 volatile Reference next;
178
179 /* Used by the garbage collector to accumulate Reference objects that need
180 * to be revisited in order to decide whether they should be notified.
181 * Also used as the link in the pending-Reference list. The discovered
182 * field and the next field are distinct to allow the enqueue() method to
183 * be applied to a Reference object while it is either in the
184 * pending-Reference list or in the garbage collector's discovered set.
185 *
186 * When active: null or next element in a discovered reference list
187 * maintained by the GC (or this if last)
188 * pending: next element in the pending-Reference list (null if last)
189 * inactive: null
190 */
191 private transient Reference<?> discovered;
192
193
194 /* High-priority thread to enqueue pending References
195 */
196 private static class ReferenceHandler extends Thread {
197 ReferenceHandler(ThreadGroup g, String name) {
198 super(g, null, name, 0, false);
199 }
200
201 public void run() {
202 while (true) {
203 processPendingReferences();
204 }
205 }
206 }
207
208 /*
209 * Atomically get and clear (set to null) the VM's pending-Reference list.
210 */
211 private static native Reference<?> getAndClearReferencePendingList();
212
213 /*
214 * Test whether the VM's pending-Reference list contains any entries.
215 */
216 private static native boolean hasReferencePendingList();
217
218 /*
219 * Wait until the VM's pending-Reference list may be non-null.
220 */
221 private static native void waitForReferencePendingList();
222
223 /*
224 * Enqueue a Reference taken from the pending list. Calling this method
225 * takes us from the Reference<?> domain of the pending list elements to
226 * having a Reference<T> with a correspondingly typed queue.
227 */
228 private void enqueueFromPending() {
229 var q = queue;
230 if (q != ReferenceQueue.NULL_QUEUE) q.enqueue(this);
231 }
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<?> pendingList;
243 synchronized (processPendingLock) {
244 pendingList = getAndClearReferencePendingList();
245 processPendingActive = true;
246 }
247 while (pendingList != null) {
248 Reference<?> ref = pendingList;
249 pendingList = ref.discovered;
250 ref.discovered = null;
251 ref.enqueueFromPending();
252 }
253 // Notify any waiters of completion of current round.
254 synchronized (processPendingLock) {
255 processPendingActive = false;
256 processPendingLock.notifyAll();
257 }
258 }
259
260 // Wait for progress in reference processing.
261 //
262 // Returns true after waiting (for notification from the reference
263 // processing thread) if either (1) the VM has any pending
264 // references, or (2) the reference processing thread is
265 // processing references. Otherwise, returns false immediately.
266 private static boolean waitForReferenceProcessing()
267 throws InterruptedException
268 {
269 synchronized (processPendingLock) {
270 if (processPendingActive || hasReferencePendingList()) {
271 // Wait for progress, not necessarily completion.
272 processPendingLock.wait();
273 return true;
274 } else {
275 return false;
276 }
277 }
278 }
279
280 /**
281 * Start the Reference Handler thread as a daemon thread.
282 */
283 static void startReferenceHandlerThread(ThreadGroup tg) {
284 Thread handler = new ReferenceHandler(tg, "Reference Handler");
285 /* If there were a special system-only priority greater than
286 * MAX_PRIORITY, it would be used here
287 */
288 handler.setPriority(Thread.MAX_PRIORITY);
289 handler.setDaemon(true);
290 handler.start();
291 }
292
293 static {
294 runtimeSetup();
295 }
296
297 @AOTRuntimeSetup
298 private static void runtimeSetup() {
299 // provide access in SharedSecrets
300 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
301 @Override
302 public void startThreads() {
303 ThreadGroup tg = Thread.currentThread().getThreadGroup();
304 for (ThreadGroup tgn = tg;
305 tgn != null;
306 tg = tgn, tgn = tg.getParent());
307 Reference.startReferenceHandlerThread(tg);
308 Finalizer.startFinalizerThread(tg);
309 }
310
311 @Override
312 public boolean waitForReferenceProcessing()
313 throws InterruptedException
314 {
315 return Reference.waitForReferenceProcessing();
316 }
317
318 @Override
319 public void runFinalization() {
320 Finalizer.runFinalization();
321 }
322 });
323 }
324
325 /* -- Referent accessor and setters -- */
326
327 /**
328 * Returns this reference object's referent. If this reference object has
329 * been cleared, either by the program or by the garbage collector, then
330 * this method returns {@code null}.
331 *
332 * @apiNote
333 * This method returns a strong reference to the referent. This may cause
334 * the garbage collector to treat it as strongly reachable until some later
335 * collection cycle. The {@link #refersTo(Object) refersTo} method can be
336 * used to avoid such strengthening when testing whether some object is
337 * the referent of a reference object; that is, use {@code ref.refersTo(obj)}
338 * rather than {@code ref.get() == obj}.
339 *
340 * @return The object to which this reference refers, or
341 * {@code null} if this reference object has been cleared
342 * @see #refersTo
343 */
344 public T get() {
345 return get0();
346 }
347
348 /* Implementation of get(). This method exists to avoid making get() all
349 * of virtual, native, and intrinsic candidate. That could have the
350 * undesirable effect of having the native method used instead of the
351 * intrinsic when devirtualization fails.
352 */
353 @IntrinsicCandidate
354 private native T get0();
355
356 /**
357 * Tests if the referent of this reference object is {@code obj}.
358 * Using a {@code null} {@code obj} returns {@code true} if the
359 * reference object has been cleared.
360 *
361 * @param obj the object to compare with this reference object's referent
362 * @return {@code true} if {@code obj} is the referent of this reference object
363 * @since 16
364 */
365 public final boolean refersTo(T obj) {
366 return refersToImpl(obj);
367 }
368
369 /* Implementation of refersTo(), overridden for phantom references.
370 * This method exists only to avoid making refersTo0() virtual. Making
371 * refersTo0() virtual has the undesirable effect of C2 often preferring
372 * to call the native implementation over the intrinsic.
373 */
374 boolean refersToImpl(T obj) {
375 return refersTo0(obj);
376 }
377
378 @IntrinsicCandidate
379 private native boolean refersTo0(Object o);
380
381 /**
382 * Clears this reference object. Invoking this method does not enqueue this
383 * object, and the garbage collector will not clear or enqueue this object.
384 *
385 * <p>When the garbage collector or the {@link #enqueue()} method clear
386 * references they do so directly, without invoking this method.
387 *
388 * @apiNote
389 * There is a potential race condition with the garbage collector. When this
390 * method is called, the garbage collector may already be in the process of
391 * (or already completed) clearing and/or enqueueing this reference.
392 * Avoid this race by ensuring the referent remains strongly reachable until
393 * after the call to clear(), using {@link #reachabilityFence(Object)} if
394 * necessary.
395 */
396 public void clear() {
397 clearImpl();
398 }
399
400 /* Implementation of clear(). A simple assignment of the referent field
401 * won't do for some garbage collectors. There is the override for phantom
402 * references, which requires different semantics. This method is also
403 * used by enqueue().
404 *
405 * <p>This method exists only to avoid making clear0() virtual. Making
406 * clear0() virtual has the undesirable effect of C2 often preferring
407 * to call the native implementation over the intrinsic.
408 */
409 void clearImpl() {
410 clear0();
411 }
412
413 @IntrinsicCandidate
414 private native void clear0();
415
416 /* -- Operations on inactive FinalReferences -- */
417
418 /* These functions are only used by FinalReference, and must only be
419 * called after the reference becomes inactive. While active, a
420 * FinalReference is considered weak but the referent is not normally
421 * accessed. Once a FinalReference becomes inactive it is considered a
422 * strong reference. These functions are used to bypass the
423 * corresponding weak implementations, directly accessing the referent
424 * field with strong semantics.
425 */
426
427 /**
428 * Load referent with strong semantics.
429 */
430 T getFromInactiveFinalReference() {
431 assert this instanceof FinalReference;
432 assert next != null; // I.e. FinalReference is inactive
433 return this.referent;
434 }
435
436 /**
437 * Clear referent with strong semantics.
438 */
439 void clearInactiveFinalReference() {
440 assert this instanceof FinalReference;
441 assert next != null; // I.e. FinalReference is inactive
442 this.referent = null;
443 }
444
445 /* -- Queue operations -- */
446
447 /**
448 * Tests if this reference object is in its associated queue, if any.
449 * This method returns {@code true} only if all of the following conditions
450 * are met:
451 * <ul>
452 * <li>this reference object was registered with a queue when it was created; and
453 * <li>the garbage collector has added this reference object to the queue
454 * or {@link #enqueue()} is called; and
455 * <li>this reference object is not yet removed from the queue.
456 * </ul>
457 * Otherwise, this method returns {@code false}.
458 * This method may return {@code false} if this reference object has been cleared
459 * but not enqueued due to the race condition.
460 *
461 * @deprecated
462 * This method was originally specified to test if a reference object has
463 * been cleared and enqueued but was never implemented to do this test.
464 * This method could be misused due to the inherent race condition
465 * or without an associated {@code ReferenceQueue}.
466 * An application relying on this method to release critical resources
467 * could cause serious performance issue.
468 * An application should use {@link ReferenceQueue} to reliably determine
469 * what reference objects that have been enqueued or
470 * {@link #refersTo(Object) refersTo(null)} to determine if this reference
471 * object has been cleared.
472 *
473 * @return {@code true} if and only if this reference object is
474 * in its associated queue (if any).
475 */
476 @Deprecated(since="16")
477 public boolean isEnqueued() {
478 return (this.queue == ReferenceQueue.ENQUEUED);
479 }
480
481 /**
482 * Clears this reference object, then attempts to add it to the queue with
483 * which it is registered, if any.
484 *
485 * <p>If this reference is registered with a queue but not yet enqueued,
486 * the reference is added to the queue; this method is
487 * <b><i>successful</i></b> and returns true.
488 * If this reference is not registered with a queue, or was already enqueued
489 * (by the garbage collector, or a previous call to {@code enqueue}), this
490 * method is <b><i>unsuccessful</i></b> and returns false.
491 *
492 * <p>{@linkplain java.lang.ref##MemoryConsistency Memory consistency effects}:
493 * Actions in a thread prior to a <b><i>successful</i></b> call to {@code enqueue}
494 * <a href="{@docRoot}/java.base/java/util/concurrent/package-summary.html#MemoryVisibility"><i>happen-before</i></a>
495 * the reference is removed from the queue by {@link ReferenceQueue#poll}
496 * or {@link ReferenceQueue#remove}. <b><i>Unsuccessful</i></b> calls to
497 * {@code enqueue} have no specified memory consistency effects.
498 *
499 * <p> When this method clears references it does so directly, without
500 * invoking the {@link #clear()} method. When the garbage collector clears
501 * and enqueues references it does so directly, without invoking the
502 * {@link #clear()} method or this method.
503 *
504 * @apiNote
505 * Use of this method allows the registered queue's
506 * {@link ReferenceQueue#poll} and {@link ReferenceQueue#remove} methods
507 * to return this reference even though the referent may still be strongly
508 * reachable.
509 *
510 * @return {@code true} if this reference object was successfully
511 * enqueued; {@code false} if it was already enqueued or if
512 * it was not registered with a queue when it was created
513 */
514 public boolean enqueue() {
515 clearImpl(); // Intentionally clearImpl() to dispatch to overridden method, if needed
516 return this.queue.enqueue(this);
517 }
518
519 /**
520 * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be
521 * meaningfully cloned. Construct a new {@code Reference} instead.
522 *
523 * @return never returns normally
524 * @throws CloneNotSupportedException always
525 */
526 @Override
527 protected Object clone() throws CloneNotSupportedException {
528 throw new CloneNotSupportedException();
529 }
530
531 /* -- Constructors -- */
532
533 Reference(T referent) {
534 this(referent, null);
535 }
536
537 Reference(T referent, ReferenceQueue<? super T> queue) {
538 this.referent = referent;
539 this.queue = (queue == null) ? ReferenceQueue.NULL_QUEUE : queue;
540 }
541
542 /**
543 * Ensures that the given object remains
544 * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>.
545 * This reachability is assured regardless of any optimizing transformations
546 * the virtual machine may perform that might otherwise allow the object to
547 * become unreachable (see JLS {@jls 12.6.1}). Thus, the given object is not
548 * reclaimable by garbage collection at least until after the invocation of
549 * this method. References to the given object will not be cleared (or
550 * enqueued, if applicable) by the garbage collector until after invocation
551 * of this method.
552 * Invocation of this method does not itself initiate reference processing,
553 * garbage collection, or finalization.
554 *
555 * <p> This method establishes an ordering for <em>strong reachability</em>
556 * with respect to garbage collection. It controls relations that are
557 * otherwise only implicit in a program -- the reachability conditions
558 * triggering garbage collection. This method is applicable only
559 * when reclamation may have visible effects,
560 * such as for objects that use finalizers or {@link Cleaner}, or code that
561 * performs {@linkplain java.lang.ref reference processing}.
562 *
563 * <p>{@linkplain java.lang.ref##MemoryConsistency Memory consistency effects}:
564 * Actions in a thread prior to calling {@code reachabilityFence(x)}
565 * <a href="{@docRoot}/java.base/java/util/concurrent/package-summary.html#MemoryVisibility"><i>happen-before</i></a>
566 * the garbage collector clears any reference to {@code x}.
567 *
568 * @apiNote
569 * Reference processing or finalization can occur after an object becomes
570 * unreachable. An object can become unreachable when the virtual machine
571 * detects that there is no further need for the object (other than for
572 * running a finalizer). In the course of optimization, the virtual machine
573 * can reorder operations of an object's methods such that the object
574 * becomes unneeded earlier than might naively be expected —
575 * including while a method of the object is still running. For instance,
576 * the VM can move the loading of <em>values</em> from the object's fields
577 * to occur earlier. The object itself is then no longer needed and becomes
578 * unreachable, and the method can continue running using the obtained values.
579 * This may have surprising and undesirable effects when using a Cleaner or
580 * finalizer for cleanup: there is a race between the
581 * program thread running the method, and the cleanup thread running the
582 * Cleaner or finalizer. The cleanup thread could free a
583 * resource, followed by the program thread (still running the method)
584 * attempting to access the now-already-freed resource.
585 * Use of {@code reachabilityFence} can prevent this race by ensuring that the
586 * object remains strongly reachable.
587 * <p>
588 * The following is an example in which the bookkeeping associated with a class is
589 * managed through array indices. Here, method {@code action} uses a
590 * {@code reachabilityFence} to ensure that the {@code Resource} object is
591 * not reclaimed before bookkeeping on an associated
592 * {@code ExternalResource} has been performed; specifically, to
593 * ensure that the array slot holding the {@code ExternalResource} is not
594 * nulled out in method {@link Object#finalize}, which may otherwise run
595 * concurrently.
596 *
597 * {@snippet :
598 * class Resource {
599 * private static ExternalResource[] externalResourceArray = ...
600 *
601 * int myIndex;
602 * Resource(...) {
603 * this.myIndex = ...
604 * externalResourceArray[myIndex] = ...;
605 * ...
606 * }
607 * protected void finalize() {
608 * externalResourceArray[this.myIndex] = null;
609 * ...
610 * }
611 * public void action() {
612 * try {
613 * // ...
614 * int i = this.myIndex; // last use of 'this' Resource in action()
615 * Resource.update(externalResourceArray[i]);
616 * } finally {
617 * Reference.reachabilityFence(this);
618 * }
619 * }
620 * private static void update(ExternalResource ext) {
621 * ext.status = ...;
622 * }
623 * }
624 * }
625 *
626 * The invocation of {@code reachabilityFence} is
627 * placed <em>after</em> the call to {@code update}, to ensure that the
628 * array slot is not nulled out by {@link Object#finalize} before the
629 * update, even if the call to {@code action} was the last use of this
630 * object. This might be the case if, for example, a usage in a user program
631 * had the form {@code new Resource().action();} which retains no other
632 * reference to this {@code Resource}.
633 * The {@code reachabilityFence} call is placed in a {@code finally} block to
634 * ensure that it is invoked across all paths in the method. A more complex
635 * method might need further precautions to ensure that
636 * {@code reachabilityFence} is encountered along all code paths.
637 *
638 * <p> Method {@code reachabilityFence} is not required in constructions
639 * that themselves ensure reachability. For example, because objects that
640 * are locked cannot, in general, be reclaimed, it would suffice if all
641 * accesses of the object, in all methods of class {@code Resource}
642 * (including {@code finalize}) were enclosed in {@code synchronized (this)}
643 * blocks. (Further, such blocks must not include infinite loops, or
644 * themselves be unreachable, which fall into the corner case exceptions to
645 * the "in general" disclaimer.) However, method {@code reachabilityFence}
646 * remains a better option in cases where synchronization is not as efficient,
647 * desirable, or possible; for example because it would encounter deadlock.
648 *
649 * @param ref the reference to the object to keep strongly reachable. If
650 * {@code null}, this method has no effect.
651 * @since 9
652 */
653 @ForceInline
654 public static void reachabilityFence(Object ref) {
655 // Does nothing. This method is annotated with @ForceInline to eliminate
656 // most of the overhead that using @DontInline would cause with the
657 // HotSpot JVM, when this fence is used in a wide variety of situations.
658 // HotSpot JVM retains the ref and does not GC it before a call to
659 // this method, because the JIT-compilers do not have GC-only safepoints.
660 }
661 }