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