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