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