1 /*
  2  * Copyright (c) 1997, 2024, 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.misc.Unsafe;
 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 import jdk.internal.ref.Cleaner;
 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 
 57 public abstract sealed class Reference<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; next = this.
 90      *
 91      *   Unregistered: Not associated with a queue when created.
 92      *   queue = ReferenceQueue.NULL.
 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
175      *    unregistered: ReferenceQueue.NULL
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             // pre-load and initialize Cleaner class so that we don't
213             // get into trouble later in the run loop if there's
214             // memory shortage while loading/initializing it lazily.
215             Unsafe.getUnsafe().ensureClassInitialized(Cleaner.class);
216 
217             while (true) {
218                 processPendingReferences();
219             }
220         }
221     }
222 
223     /*
224      * Atomically get and clear (set to null) the VM's pending-Reference list.
225      */
226     private static native Reference<?> getAndClearReferencePendingList();
227 
228     /*
229      * Test whether the VM's pending-Reference list contains any entries.
230      */
231     private static native boolean hasReferencePendingList();
232 
233     /*
234      * Wait until the VM's pending-Reference list may be non-null.
235      */
236     private static native void waitForReferencePendingList();
237 
238     /*
239      * Enqueue a Reference taken from the pending list.  Calling this method
240      * takes us from the Reference<?> domain of the pending list elements to
241      * having a Reference<T> with a correspondingly typed queue.
242      */
243     private void enqueueFromPending() {
244         var q = queue;
245         if (q != ReferenceQueue.NULL) q.enqueue(this);
246     }
247 
248     private static final Object processPendingLock = new Object();
249     private static boolean processPendingActive = false;
250 
251     private static void processPendingReferences() {
252         // Only the singleton reference processing thread calls
253         // waitForReferencePendingList() and getAndClearReferencePendingList().
254         // These are separate operations to avoid a race with other threads
255         // that are calling waitForReferenceProcessing().
256         waitForReferencePendingList();
257         Reference<?> pendingList;
258         synchronized (processPendingLock) {
259             pendingList = getAndClearReferencePendingList();
260             processPendingActive = true;
261         }
262         while (pendingList != null) {
263             Reference<?> ref = pendingList;
264             pendingList = ref.discovered;
265             ref.discovered = null;
266 
267             if (ref instanceof Cleaner) {
268                 ((Cleaner)ref).clean();
269                 // Notify any waiters that progress has been made.
270                 // This improves latency for nio.Bits waiters, which
271                 // are the only important ones.
272                 synchronized (processPendingLock) {
273                     processPendingLock.notifyAll();
274                 }
275             } else {
276                 ref.enqueueFromPending();
277             }
278         }
279         // Notify any waiters of completion of current round.
280         synchronized (processPendingLock) {
281             processPendingActive = false;
282             processPendingLock.notifyAll();
283         }
284     }
285 
286     // Wait for progress in reference processing.
287     //
288     // Returns true after waiting (for notification from the reference
289     // processing thread) if either (1) the VM has any pending
290     // references, or (2) the reference processing thread is
291     // processing references. Otherwise, returns false immediately.
292     private static boolean waitForReferenceProcessing()
293         throws InterruptedException
294     {
295         synchronized (processPendingLock) {
296             if (processPendingActive || hasReferencePendingList()) {
297                 // Wait for progress, not necessarily completion.
298                 processPendingLock.wait();
299                 return true;
300             } else {
301                 return false;
302             }
303         }
304     }
305 
306     /**
307      * Start the Reference Handler thread as a daemon thread.
308      */
309     static void startReferenceHandlerThread(ThreadGroup tg) {
310         Thread handler = new ReferenceHandler(tg, "Reference Handler");
311         /* If there were a special system-only priority greater than
312          * MAX_PRIORITY, it would be used here
313          */
314         handler.setPriority(Thread.MAX_PRIORITY);
315         handler.setDaemon(true);
316         handler.start();
317     }
318 
319     static {
320         // provide access in SharedSecrets
321         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
322             @Override
323             public void startThreads() {
324                 ThreadGroup tg = Thread.currentThread().getThreadGroup();
325                 for (ThreadGroup tgn = tg;
326                      tgn != null;
327                      tg = tgn, tgn = tg.getParent());
328                 Reference.startReferenceHandlerThread(tg);
329                 Finalizer.startFinalizerThread(tg);
330             }
331 
332             @Override
333             public boolean waitForReferenceProcessing()
334                 throws InterruptedException
335             {
336                 return Reference.waitForReferenceProcessing();
337             }
338 
339             @Override
340             public void runFinalization() {
341                 Finalizer.runFinalization();
342             }
343         });
344     }
345 
346     /* -- Referent accessor and setters -- */
347 
348     /**
349      * Returns this reference object's referent.  If this reference object has
350      * been cleared, either by the program or by the garbage collector, then
351      * this method returns {@code null}.
352      *
353      * @apiNote
354      * This method returns a strong reference to the referent. This may cause
355      * the garbage collector to treat it as strongly reachable until some later
356      * collection cycle.  The {@link #refersTo(Object) refersTo} method can be
357      * used to avoid such strengthening when testing whether some object is
358      * the referent of a reference object; that is, use {@code ref.refersTo(obj)}
359      * rather than {@code ref.get() == obj}.
360      *
361      * @return   The object to which this reference refers, or
362      *           {@code null} if this reference object has been cleared
363      * @see #refersTo
364      */
365     @IntrinsicCandidate
366     public T get() {
367         return this.referent;
368     }
369 
370     /**
371      * Tests if the referent of this reference object is {@code obj}.
372      * Using a {@code null} {@code obj} returns {@code true} if the
373      * reference object has been cleared.
374      *
375      * @param  obj the object to compare with this reference object's referent
376      * @return {@code true} if {@code obj} is the referent of this reference object
377      * @since 16
378      */
379     public final boolean refersTo(T obj) {
380         return refersToImpl(obj);
381     }
382 
383     /* Implementation of refersTo(), overridden for phantom references.
384      * This method exists only to avoid making refersTo0() virtual. Making
385      * refersTo0() virtual has the undesirable effect of C2 often preferring
386      * to call the native implementation over the intrinsic.
387      */
388     boolean refersToImpl(T obj) {
389         return refersTo0(obj);
390     }
391 
392     @IntrinsicCandidate
393     private native boolean refersTo0(Object o);
394 
395     /**
396      * Clears this reference object. Invoking this method does not enqueue this
397      * object, and the garbage collector will not clear or enqueue this object.
398      *
399      * <p>When the garbage collector or the {@link #enqueue()} method clear
400      * references they do so directly, without invoking this method.
401      *
402      * @apiNote
403      * There is a potential race condition with the garbage collector. When this
404      * method is called, the garbage collector may already be in the process of
405      * (or already completed) clearing and/or enqueueing this reference.
406      * Avoid this race by ensuring the referent remains strongly reachable until
407      * after the call to clear(), using {@link #reachabilityFence(Object)} if
408      * necessary.
409      */
410     public void clear() {
411         clearImpl();
412     }
413 
414     /* Implementation of clear(). A simple assignment of the referent field
415      * won't do for some garbage collectors. There is the override for phantom
416      * references, which requires different semantics. This method is also
417      * used by enqueue().
418      *
419      * <p>This method exists only to avoid making clear0() virtual. Making
420      * clear0() virtual has the undesirable effect of C2 often preferring
421      * to call the native implementation over the intrinsic.
422      */
423     void clearImpl() {
424         clear0();
425     }
426 
427     @IntrinsicCandidate
428     private native void clear0();
429 
430     /* -- Operations on inactive FinalReferences -- */
431 
432     /* These functions are only used by FinalReference, and must only be
433      * called after the reference becomes inactive. While active, a
434      * FinalReference is considered weak but the referent is not normally
435      * accessed. Once a FinalReference becomes inactive it is considered a
436      * strong reference. These functions are used to bypass the
437      * corresponding weak implementations, directly accessing the referent
438      * field with strong semantics.
439      */
440 
441     /**
442      * Load referent with strong semantics.
443      */
444     T getFromInactiveFinalReference() {
445         assert this instanceof FinalReference;
446         assert next != null; // I.e. FinalReference is inactive
447         return this.referent;
448     }
449 
450     /**
451      * Clear referent with strong semantics.
452      */
453     void clearInactiveFinalReference() {
454         assert this instanceof FinalReference;
455         assert next != null; // I.e. FinalReference is inactive
456         this.referent = null;
457     }
458 
459     /* -- Queue operations -- */
460 
461     /**
462      * Tests if this reference object is in its associated queue, if any.
463      * This method returns {@code true} only if all of the following conditions
464      * are met:
465      * <ul>
466      * <li>this reference object was registered with a queue when it was created; and
467      * <li>the garbage collector has added this reference object to the queue
468      *     or {@link #enqueue()} is called; and
469      * <li>this reference object is not yet removed from the queue.
470      * </ul>
471      * Otherwise, this method returns {@code false}.
472      * This method may return {@code false} if this reference object has been cleared
473      * but not enqueued due to the race condition.
474      *
475      * @deprecated
476      * This method was originally specified to test if a reference object has
477      * been cleared and enqueued but was never implemented to do this test.
478      * This method could be misused due to the inherent race condition
479      * or without an associated {@code ReferenceQueue}.
480      * An application relying on this method to release critical resources
481      * could cause serious performance issue.
482      * An application should use {@link ReferenceQueue} to reliably determine
483      * what reference objects that have been enqueued or
484      * {@link #refersTo(Object) refersTo(null)} to determine if this reference
485      * object has been cleared.
486      *
487      * @return   {@code true} if and only if this reference object is
488      *           in its associated queue (if any).
489      */
490     @Deprecated(since="16")
491     public boolean isEnqueued() {
492         return (this.queue == ReferenceQueue.ENQUEUED);
493     }
494 
495     /**
496      * Clears this reference object, then attempts to add it to the queue with
497      * which it is registered, if any.
498      *
499      * <p>If this reference is registered with a queue but not yet enqueued,
500      * the reference is added to the queue; this method is
501      * <b><i>successful</i></b> and returns true.
502      * If this reference is not registered with a queue, or was already enqueued
503      * (by the garbage collector, or a previous call to {@code enqueue}), this
504      * method is <b><i>unsuccessful</i></b> and returns false.
505      *
506      * <p>{@linkplain java.lang.ref##MemoryConsistency Memory consistency effects}:
507      * Actions in a thread prior to a <b><i>successful</i></b> call to {@code enqueue}
508      * <a href="{@docRoot}/java.base/java/util/concurrent/package-summary.html#MemoryVisibility"><i>happen-before</i></a>
509      * the reference is removed from the queue by {@link ReferenceQueue#poll}
510      * or {@link ReferenceQueue#remove}. <b><i>Unsuccessful</i></b> calls to
511      * {@code enqueue} have no specified memory consistency effects.
512      *
513      * <p> When this method clears references it does so directly, without
514      * invoking the {@link #clear()} method. When the garbage collector clears
515      * and enqueues references it does so directly, without invoking the
516      * {@link #clear()} method or this method.
517      *
518      * @apiNote
519      * Use of this method allows the registered queue's
520      * {@link ReferenceQueue#poll} and {@link ReferenceQueue#remove} methods
521      * to return this reference even though the referent may still be strongly
522      * reachable.
523      *
524      * @return   {@code true} if this reference object was successfully
525      *           enqueued; {@code false} if it was already enqueued or if
526      *           it was not registered with a queue when it was created
527      */
528     public boolean enqueue() {
529         clearImpl(); // Intentionally clearImpl() to dispatch to overridden method, if needed
530         return this.queue.enqueue(this);
531     }
532 
533     /**
534      * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be
535      * meaningfully cloned. Construct a new {@code Reference} instead.
536      *
537      * @return never returns normally
538      * @throws  CloneNotSupportedException always
539      */
540     @Override
541     protected Object clone() throws CloneNotSupportedException {
542         throw new CloneNotSupportedException();
543     }
544 
545     /* -- Constructors -- */
546 
547     Reference(T referent) {
548         this(referent, null);
549     }
550 
551     Reference(T referent, ReferenceQueue<? super T> queue) {
552         if (referent != null) {
553             Objects.requireIdentity(referent);
554         }
555         this.referent = referent;
556         this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
557     }
558 
559     /**
560      * Ensures that the given object remains
561      * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>.
562      * This reachability is assured regardless of any optimizing transformations
563      * the virtual machine may perform that might otherwise allow the object to
564      * become unreachable (see JLS {@jls 12.6.1}). Thus, the given object is not
565      * reclaimable by garbage collection at least until after the invocation of
566      * this method. References to the given object will not be cleared (or
567      * enqueued, if applicable) by the garbage collector until after invocation
568      * of this method.
569      * Invocation of this method does not itself initiate reference processing,
570      * garbage collection, or finalization.
571      *
572      * <p> This method establishes an ordering for <em>strong reachability</em>
573      * with respect to garbage collection.  It controls relations that are
574      * otherwise only implicit in a program -- the reachability conditions
575      * triggering garbage collection.  This method is applicable only
576      * when reclamation may have visible effects,
577      * such as for objects that use finalizers or {@link Cleaner}, or code that
578      * performs {@linkplain java.lang.ref reference processing}.
579      *
580      * <p>{@linkplain java.lang.ref##MemoryConsistency Memory consistency effects}:
581      * Actions in a thread prior to calling {@code reachabilityFence(x)}
582      * <a href="{@docRoot}/java.base/java/util/concurrent/package-summary.html#MemoryVisibility"><i>happen-before</i></a>
583      * the garbage collector clears any reference to {@code x}.
584      *
585      * @apiNote
586      * Reference processing or finalization can occur after an object becomes
587      * unreachable. An object can become unreachable when the virtual machine
588      * detects that there is no further need for the object (other than for
589      * running a finalizer). In the course of optimization, the virtual machine
590      * can reorder operations of an object's methods such that the object
591      * becomes unneeded earlier than might naively be expected &mdash;
592      * including while a method of the object is still running. For instance,
593      * the VM can move the loading of <em>values</em> from the object's fields
594      * to occur earlier. The object itself is then no longer needed and becomes
595      * unreachable, and the method can continue running using the obtained values.
596      * This may have surprising and undesirable effects when using a Cleaner or
597      * finalizer for cleanup: there is a race between the
598      * program thread running the method, and the cleanup thread running the
599      * Cleaner or finalizer. The cleanup thread could free a
600      * resource, followed by the program thread (still running the method)
601      * attempting to access the now-already-freed resource.
602      * Use of {@code reachabilityFence} can prevent this race by ensuring that the
603      * object remains strongly reachable.
604      * <p>
605      * The following is an example in which the bookkeeping associated with a class is
606      * managed through array indices.  Here, method {@code action} uses a
607      * {@code reachabilityFence} to ensure that the {@code Resource} object is
608      * not reclaimed before bookkeeping on an associated
609      * {@code ExternalResource} has been performed; specifically, to
610      * ensure that the array slot holding the {@code ExternalResource} is not
611      * nulled out in method {@link Object#finalize}, which may otherwise run
612      * concurrently.
613      *
614      * {@snippet :
615      * class Resource {
616      *   private static ExternalResource[] externalResourceArray = ...
617      *
618      *   int myIndex;
619      *   Resource(...) {
620      *     this.myIndex = ...
621      *     externalResourceArray[myIndex] = ...;
622      *     ...
623      *   }
624      *   protected void finalize() {
625      *     externalResourceArray[this.myIndex] = null;
626      *     ...
627      *   }
628      *   public void action() {
629      *     try {
630      *       // ...
631      *       int i = this.myIndex; // last use of 'this' Resource in action()
632      *       Resource.update(externalResourceArray[i]);
633      *     } finally {
634      *       Reference.reachabilityFence(this);
635      *     }
636      *   }
637      *   private static void update(ExternalResource ext) {
638      *     ext.status = ...;
639      *   }
640      * }
641      * }
642      *
643      * The invocation of {@code reachabilityFence} is
644      * placed <em>after</em> the call to {@code update}, to ensure that the
645      * array slot is not nulled out by {@link Object#finalize} before the
646      * update, even if the call to {@code action} was the last use of this
647      * object.  This might be the case if, for example, a usage in a user program
648      * had the form {@code new Resource().action();} which retains no other
649      * reference to this {@code Resource}.
650      * The {@code reachabilityFence} call is placed in a {@code finally} block to
651      * ensure that it is invoked across all paths in the method. A more complex
652      * method might need further precautions to ensure that
653      * {@code reachabilityFence} is encountered along all code paths.
654      *
655      * <p> Method {@code reachabilityFence} is not required in constructions
656      * that themselves ensure reachability.  For example, because objects that
657      * are locked cannot, in general, be reclaimed, it would suffice if all
658      * accesses of the object, in all methods of class {@code Resource}
659      * (including {@code finalize}) were enclosed in {@code synchronized (this)}
660      * blocks.  (Further, such blocks must not include infinite loops, or
661      * themselves be unreachable, which fall into the corner case exceptions to
662      * the "in general" disclaimer.)  However, method {@code reachabilityFence}
663      * remains a better option in cases where synchronization is not as efficient,
664      * desirable, or possible; for example because it would encounter deadlock.
665      *
666      * @param ref the reference to the object to keep strongly reachable. If
667      * {@code null}, this method has no effect.
668      * @since 9
669      */
670     @ForceInline
671     public static void reachabilityFence(Object ref) {
672         // Does nothing. This method is annotated with @ForceInline to eliminate
673         // most of the overhead that using @DontInline would cause with the
674         // HotSpot JVM, when this fence is used in a wide variety of situations.
675         // HotSpot JVM retains the ref and does not GC it before a call to
676         // this method, because the JIT-compilers do not have GC-only safepoints.
677     }
678 }