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