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  * <p>
 43  * The referent must be an {@linkplain Objects#hasIdentity(Object) identity object}.
 44  * Attempts to create a reference to a value object result in an {@link IdentityException}.
 45  * @param <T> the type of the referent
 46  *
 47  * @author   Mark Reinhold
 48  * @since    1.2
 49  * @sealedGraph
 50  */
 51 
 52 public abstract sealed class Reference<T>
 53     permits PhantomReference, SoftReference, WeakReference, FinalReference {
 54 
 55     /* The state of a Reference object is characterized by two attributes.  It
 56      * may be either "active", "pending", or "inactive".  It may also be
 57      * either "registered", "enqueued", "dequeued", or "unregistered".
 58      *
 59      *   Active: Subject to special treatment by the garbage collector.  Some
 60      *   time after the collector detects that the reachability of the
 61      *   referent has changed to the appropriate state, the collector
 62      *   "notifies" the reference, changing the state to either "pending" or
 63      *   "inactive".
 64      *   referent != null; discovered = null, or in GC discovered list.
 65      *
 66      *   Pending: An element of the pending-Reference list, waiting to be
 67      *   processed by the ReferenceHandler thread.  The pending-Reference
 68      *   list is linked through the discovered fields of references in the
 69      *   list.
 70      *   referent = null; discovered = next element in pending-Reference list.
 71      *
 72      *   Inactive: Neither Active nor Pending.
 73      *   referent = null.
 74      *
 75      *   Registered: Associated with a queue when created, and not yet added
 76      *   to the queue.
 77      *   queue = the associated queue.
 78      *
 79      *   Enqueued: Added to the associated queue, and not yet removed.
 80      *   queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to
 81      *   indicate end of list.
 82      *
 83      *   Dequeued: Added to the associated queue and then removed.
 84      *   queue = ReferenceQueue.NULL; next = this.
 85      *
 86      *   Unregistered: Not associated with a queue when created.
 87      *   queue = ReferenceQueue.NULL.
 88      *
 89      * The collector only needs to examine the referent field and the
 90      * discovered field to determine whether a (non-FinalReference) Reference
 91      * object needs special treatment.  If the referent is non-null and not
 92      * known to be live, then it may need to be discovered for possible later
 93      * notification.  But if the discovered field is non-null, then it has
 94      * already been discovered.
 95      *
 96      * FinalReference (which exists to support finalization) differs from
 97      * other references, because a FinalReference is not cleared when
 98      * notified.  The referent being null or not cannot be used to distinguish
 99      * between the active state and pending or inactive states.  However,
100      * FinalReferences do not support enqueue().  Instead, the next field of a
101      * FinalReference object is set to "this" when it is added to the
102      * pending-Reference list.  The use of "this" as the value of next in the
103      * enqueued and dequeued states maintains the non-active state.  An
104      * additional check that the next field is null is required to determine
105      * that a FinalReference object is active.
106      *
107      * Initial states:
108      *   [active/registered]
109      *   [active/unregistered] [1]
110      *
111      * Transitions:
112      *                            clear [2]
113      *   [active/registered]     ------->   [inactive/registered]
114      *          |                                 |
115      *          |                                 | enqueue
116      *          | GC              enqueue [2]     |
117      *          |                -----------------|
118      *          |                                 |
119      *          v                                 |
120      *   [pending/registered]    ---              v
121      *          |                   | ReferenceHandler
122      *          | enqueue [2]       |--->   [inactive/enqueued]
123      *          v                   |             |
124      *   [pending/enqueued]      ---              |
125      *          |                                 | poll/remove
126      *          | poll/remove                     | + clear [4]
127      *          |                                 |
128      *          v            ReferenceHandler     v
129      *   [pending/dequeued]      ------>    [inactive/dequeued]
130      *
131      *
132      *                           clear/enqueue/GC [3]
133      *   [active/unregistered]   ------
134      *          |                      |
135      *          | GC                   |
136      *          |                      |--> [inactive/unregistered]
137      *          v                      |
138      *   [pending/unregistered]  ------
139      *                           ReferenceHandler
140      *
141      * Terminal states:
142      *   [inactive/dequeued]
143      *   [inactive/unregistered]
144      *
145      * Unreachable states (because enqueue also clears):
146      *   [active/enqueued]
147      *   [active/dequeued]
148      *
149      * [1] Unregistered is not permitted for FinalReferences.
150      *
151      * [2] These transitions are not possible for FinalReferences, making
152      * [pending/enqueued], [pending/dequeued], and [inactive/registered]
153      * unreachable.
154      *
155      * [3] The garbage collector may directly transition a Reference
156      * from [active/unregistered] to [inactive/unregistered],
157      * bypassing the pending-Reference list.
158      *
159      * [4] The queue handler for FinalReferences also clears the reference.
160      */
161 
162     private T referent;         /* Treated specially by GC */
163 
164     /* The queue this reference gets enqueued to by GC notification or by
165      * calling enqueue().
166      *
167      * When registered: the queue with which this reference is registered.
168      *        enqueued: ReferenceQueue.ENQUEUE
169      *        dequeued: ReferenceQueue.NULL
170      *    unregistered: ReferenceQueue.NULL
171      */
172     volatile ReferenceQueue<? super T> queue;
173 
174     /* The link in a ReferenceQueue's list of Reference objects.
175      *
176      * When registered: null
177      *        enqueued: next element in queue (or this if last)
178      *        dequeued: this (marking FinalReferences as inactive)
179      *    unregistered: null
180      */
181     @SuppressWarnings("rawtypes")
182     volatile Reference next;
183 
184     /* Used by the garbage collector to accumulate Reference objects that need
185      * to be revisited in order to decide whether they should be notified.
186      * Also used as the link in the pending-Reference list.  The discovered
187      * field and the next field are distinct to allow the enqueue() method to
188      * be applied to a Reference object while it is either in the
189      * pending-Reference list or in the garbage collector's discovered set.
190      *
191      * When active: null or next element in a discovered reference list
192      *              maintained by the GC (or this if last)
193      *     pending: next element in the pending-Reference list (null if last)
194      *    inactive: null
195      */
196     private transient Reference<?> discovered;
197 
198 
199     /* High-priority thread to enqueue pending References
200      */
201     private static class ReferenceHandler extends Thread {
202         ReferenceHandler(ThreadGroup g, String name) {
203             super(g, null, name, 0, false);
204         }
205 
206         public void run() {
207             // pre-load and initialize Cleaner class so that we don't
208             // get into trouble later in the run loop if there's
209             // memory shortage while loading/initializing it lazily.
210             Unsafe.getUnsafe().ensureClassInitialized(Cleaner.class);
211 
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) 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 
262             if (ref instanceof Cleaner) {
263                 ((Cleaner)ref).clean();
264                 // Notify any waiters that progress has been made.
265                 // This improves latency for nio.Bits waiters, which
266                 // are the only important ones.
267                 synchronized (processPendingLock) {
268                     processPendingLock.notifyAll();
269                 }
270             } else {
271                 ref.enqueueFromPending();
272             }
273         }
274         // Notify any waiters of completion of current round.
275         synchronized (processPendingLock) {
276             processPendingActive = false;
277             processPendingLock.notifyAll();
278         }
279     }
280 
281     // Wait for progress in reference processing.
282     //
283     // Returns true after waiting (for notification from the reference
284     // processing thread) if either (1) the VM has any pending
285     // references, or (2) the reference processing thread is
286     // processing references. Otherwise, returns false immediately.
287     private static boolean waitForReferenceProcessing()
288         throws InterruptedException
289     {
290         synchronized (processPendingLock) {
291             if (processPendingActive || hasReferencePendingList()) {
292                 // Wait for progress, not necessarily completion.
293                 processPendingLock.wait();
294                 return true;
295             } else {
296                 return false;
297             }
298         }
299     }
300 
301     /**
302      * Start the Reference Handler thread as a daemon thread.
303      */
304     static void startReferenceHandlerThread(ThreadGroup tg) {
305         Thread handler = new ReferenceHandler(tg, "Reference Handler");
306         /* If there were a special system-only priority greater than
307          * MAX_PRIORITY, it would be used here
308          */
309         handler.setPriority(Thread.MAX_PRIORITY);
310         handler.setDaemon(true);
311         handler.start();
312     }
313 
314     static {
315         // provide access in SharedSecrets
316         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
317             @Override
318             public void startThreads() {
319                 ThreadGroup tg = Thread.currentThread().getThreadGroup();
320                 for (ThreadGroup tgn = tg;
321                      tgn != null;
322                      tg = tgn, tgn = tg.getParent());
323                 Reference.startReferenceHandlerThread(tg);
324                 Finalizer.startFinalizerThread(tg);
325             }
326 
327             @Override
328             public boolean waitForReferenceProcessing()
329                 throws InterruptedException
330             {
331                 return Reference.waitForReferenceProcessing();
332             }
333 
334             @Override
335             public void runFinalization() {
336                 Finalizer.runFinalization();
337             }
338 
339             @Override
340             public <T> ReferenceQueue<T> newNativeReferenceQueue() {
341                 return new NativeReferenceQueue<T>();
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 }