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