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