1 /*
   2  * Copyright (c) 1997, 2018, 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.HotSpotIntrinsicCandidate;
  30 import jdk.internal.misc.JavaLangRefAccess;
  31 import jdk.internal.misc.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 class Reference<T> {
  45 
  46     /* The state of a Reference object is characterized by two attributes.  It
  47      * may be either "active", "pending", or "inactive".  It may also be
  48      * either "registered", "enqueued", "dequeued", or "unregistered".
  49      *
  50      * Active: Subject to special treatment by the garbage collector.  Some
  51      * time after the collector detects that the reachability of the referent
  52      * has changed to the appropriate state, the collector "notifies" the
  53      * reference, changing the state to either "pending" or "inactive".
  54      * referent != null; discovered = null, or in GC discovered list.
  55      *
  56      * Pending: An element of the pending-Reference list, waiting to be
  57      * processed by the Reference-handler thread.  The pending-Reference list
  58      * is linked through the discovered fields of references in the list.
  59      * referent = null; discovered = next element in pending-Reference list.
  60      *
  61      * Inactive: Neither Active nor Pending.
  62      * referent = null.
  63      *
  64      * Registered: Associated with a queue when created, and not yet added to
  65      * the queue.
  66      * queue = the associated queue.
  67      *
  68      * Enqueued: Added to the associated queue, and not yet removed.
  69      * queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to
  70      * indicate end of list.
  71      *
  72      * Dequeued: Added to the associated queue and then removed.
  73      * queue = ReferenceQueue.NULL; next = this.
  74      *
  75      * Unregistered: Not associated with a queue when created.
  76      * queue = ReferenceQueue.NULL.
  77      *
  78      * The collector only needs to examine the referent field and the
  79      * discovered field to determine whether a normal Reference object needs
  80      * special treatment.  If the referent is non-null and not known to be
  81      * live, then it may need to be discovered for possible later
  82      * notification.  But if the discovered field is non-null, then either (1)
  83      * it has already been discovered, or (2) it is in the pending list.
  84      *
  85      * FinalReference differs from other references, because a FinalReference
  86      * is not cleared when notified.  The referent being null or not cannot be
  87      * used to distinguish between the active state and pending or inactive
  88      * states.  However, FinalReferences do not support enqueue().  Instead,
  89      * the next field of a FinalReference object is set to the object when it
  90      * is added to the pending list, and the use of this as the value of next
  91      * in the enqueued and dequeued states maintains the non-active state.  An
  92      * additional check that the next field is null is required to determine
  93      * that a FinalReference object is active.
  94      *
  95      * Initial states:
  96      *   active/registered
  97      *   active/unregistered [1]
  98      *
  99      * Transitions:
 100      *   active/registered    -> pending/registered    - GC
 101      *                        -> inactive/registered   - clear
 102      *                        -> inactive/enqueued     - enqueue [2]
 103      *   pending/registered   -> pending/enqueued      - enqueue [2]
 104      *                        -> inactive/enqueued     - pending list processing
 105      *   pending/enqueued     -> inactive/enqueued     - pending list processing
 106      *                        -> pending/dequeued      - poll/remove
 107      *   pending/dequeued     -> inactive/dequeued     - pending list processing
 108      *   inactive/registered  -> inactive/enqueued     - enqueue [2]
 109      *   inactive/enqueued    -> inactive/dequeued     - poll/remove
 110      *
 111      *   active/unregistered  -> pending/unregistered  - GC
 112      *                        -> inactive/unregistered - GC, clear, enqueue
 113      *   pending/unregistered -> inactive/unregistered - pending list processing
 114      *
 115      * Terminal states:
 116      *   inactive/dequeued
 117      *   inactive/unregistered
 118      *
 119      * Unreachable states (because enqueue also clears):
 120      *   active/enqeued
 121      *   active/dequeued
 122      *
 123      * [1] Unregistered is not permitted for FinalReferences.
 124      *
 125      * [2] These transitions are not possible for FinalReferences, making
 126      * pending/enqueued and pending/dequeued unreachable, and
 127      * inactive/registered terminal.
 128      */
 129 
 130     private T referent;         /* Treated specially by GC */
 131 
 132     volatile ReferenceQueue<? super T> queue;
 133 
 134     /* The link in a ReferenceQueue's list of Reference objects.
 135      *
 136      * When registered: null
 137      *        enqueued: next element in queue (or this if last)
 138      *        dequeued: this (marking FinalReferences as inactive)
 139      *    unregistered: null
 140      */
 141     @SuppressWarnings("rawtypes")
 142     volatile Reference next;
 143 
 144     /* Used by the garbage collector to accumulate Reference objects that need
 145      * to be revisited in order to decide whether they should be notified.
 146      * Also used as the link in the pending-Reference list.  The discovered
 147      * field and the next field are distinct to allow the enqueue() method to
 148      * be applied to a Reference object while it is either in the
 149      * pending-Reference list or in the garbage collector's discovered set.
 150      *
 151      * When active: null or next element in a discovered reference list
 152      *              maintained by the GC (or this if last)
 153      *     pending: next element in the pending-Reference list (null if last)
 154      *    inactive: null
 155      */
 156     private transient Reference<T> discovered;
 157 
 158 
 159     /* High-priority thread to enqueue pending References
 160      */
 161     private static class ReferenceHandler extends Thread {
 162 
 163         private static void ensureClassInitialized(Class<?> clazz) {
 164             try {
 165                 Class.forName(clazz.getName(), true, clazz.getClassLoader());
 166             } catch (ClassNotFoundException e) {
 167                 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
 168             }
 169         }
 170 
 171         static {
 172             // pre-load and initialize Cleaner class so that we don't
 173             // get into trouble later in the run loop if there's
 174             // memory shortage while loading/initializing it lazily.
 175             ensureClassInitialized(Cleaner.class);
 176         }
 177 
 178         ReferenceHandler(ThreadGroup g, String name) {
 179             super(g, null, name, 0, false);
 180         }
 181 
 182         public void run() {
 183             while (true) {
 184                 processPendingReferences();
 185             }
 186         }
 187     }
 188 
 189     /*
 190      * Atomically get and clear (set to null) the VM's pending list.
 191      */
 192     private static native Reference<Object> getAndClearReferencePendingList();
 193 
 194     /*
 195      * Test whether the VM's pending list contains any entries.
 196      */
 197     private static native boolean hasReferencePendingList();
 198 
 199     /*
 200      * Wait until the VM's pending list may be non-null.
 201      */
 202     private static native void waitForReferencePendingList();
 203 
 204     private static final Object processPendingLock = new Object();
 205     private static boolean processPendingActive = false;
 206 
 207     private static void processPendingReferences() {
 208         // Only the singleton reference processing thread calls
 209         // waitForReferencePendingList() and getAndClearReferencePendingList().
 210         // These are separate operations to avoid a race with other threads
 211         // that are calling waitForReferenceProcessing().
 212         waitForReferencePendingList();
 213         Reference<Object> pendingList;
 214         synchronized (processPendingLock) {
 215             pendingList = getAndClearReferencePendingList();
 216             processPendingActive = true;
 217         }
 218         while (pendingList != null) {
 219             Reference<Object> ref = pendingList;
 220             pendingList = ref.discovered;
 221             ref.discovered = null;
 222 
 223             if (ref instanceof Cleaner) {
 224                 ((Cleaner)ref).clean();
 225                 // Notify any waiters that progress has been made.
 226                 // This improves latency for nio.Bits waiters, which
 227                 // are the only important ones.
 228                 synchronized (processPendingLock) {
 229                     processPendingLock.notifyAll();
 230                 }
 231             } else {
 232                 ReferenceQueue<? super Object> q = ref.queue;
 233                 if (q != ReferenceQueue.NULL) q.enqueue(ref);
 234             }
 235         }
 236         // Notify any waiters of completion of current round.
 237         synchronized (processPendingLock) {
 238             processPendingActive = false;
 239             processPendingLock.notifyAll();
 240         }
 241     }
 242 
 243     // Wait for progress in reference processing.
 244     //
 245     // Returns true after waiting (for notification from the reference
 246     // processing thread) if either (1) the VM has any pending
 247     // references, or (2) the reference processing thread is
 248     // processing references. Otherwise, returns false immediately.
 249     private static boolean waitForReferenceProcessing()
 250         throws InterruptedException
 251     {
 252         synchronized (processPendingLock) {
 253             if (processPendingActive || hasReferencePendingList()) {
 254                 // Wait for progress, not necessarily completion.
 255                 processPendingLock.wait();
 256                 return true;
 257             } else {
 258                 return false;
 259             }
 260         }
 261     }
 262 
 263     static {
 264         ThreadGroup tg = Thread.currentThread().getThreadGroup();
 265         for (ThreadGroup tgn = tg;
 266              tgn != null;
 267              tg = tgn, tgn = tg.getParent());
 268         Thread handler = new ReferenceHandler(tg, "Reference Handler");
 269         /* If there were a special system-only priority greater than
 270          * MAX_PRIORITY, it would be used here
 271          */
 272         handler.setPriority(Thread.MAX_PRIORITY);
 273         handler.setDaemon(true);
 274         handler.start();
 275 
 276         // provide access in SharedSecrets
 277         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
 278             @Override
 279             public boolean waitForReferenceProcessing()
 280                 throws InterruptedException
 281             {
 282                 return Reference.waitForReferenceProcessing();
 283             }
 284 
 285             @Override
 286             public void runFinalization() {
 287                 Finalizer.runFinalization();
 288             }
 289         });
 290     }
 291 
 292     /* -- Referent accessor and setters -- */
 293 
 294     /**
 295      * Returns this reference object's referent.  If this reference object has
 296      * been cleared, either by the program or by the garbage collector, then
 297      * this method returns <code>null</code>.
 298      *
 299      * @return   The object to which this reference refers, or
 300      *           <code>null</code> if this reference object has been cleared
 301      */
 302     @HotSpotIntrinsicCandidate
 303     public T get() {
 304         return this.referent;
 305     }
 306 
 307     /**
 308      * Clears this reference object.  Invoking this method will not cause this
 309      * object to be enqueued.
 310      *
 311      * <p> This method is invoked only by Java code; when the garbage collector
 312      * clears references it does so directly, without invoking this method.
 313      */
 314     public void clear() {
 315         this.referent = null;
 316     }
 317 
 318     /* -- Queue operations -- */
 319 
 320     /**
 321      * Tells whether or not this reference object has been enqueued, either by
 322      * the program or by the garbage collector.  If this reference object was
 323      * not registered with a queue when it was created, then this method will
 324      * always return <code>false</code>.
 325      *
 326      * @return   <code>true</code> if and only if this reference object has
 327      *           been enqueued
 328      */
 329     public boolean isEnqueued() {
 330         return (this.queue == ReferenceQueue.ENQUEUED);
 331     }
 332 
 333     /**
 334      * Clears this reference object and adds it to the queue with which
 335      * it is registered, if any.
 336      *
 337      * <p> This method is invoked only by Java code; when the garbage collector
 338      * enqueues references it does so directly, without invoking this method.
 339      *
 340      * @return   <code>true</code> if this reference object was successfully
 341      *           enqueued; <code>false</code> if it was already enqueued or if
 342      *           it was not registered with a queue when it was created
 343      */
 344     public boolean enqueue() {
 345         this.referent = null;
 346         return this.queue.enqueue(this);
 347     }
 348 
 349     /**
 350      * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be
 351      * meaningfully cloned. Construct a new {@code Reference} instead.
 352      *
 353      * @returns never returns normally
 354      * @throws  CloneNotSupportedException always
 355      *
 356      * @since 11
 357      */
 358     @Override
 359     protected Object clone() throws CloneNotSupportedException {
 360         throw new CloneNotSupportedException();
 361     }
 362 
 363     /* -- Constructors -- */
 364 
 365     Reference(T referent) {
 366         this(referent, null);
 367     }
 368 
 369     Reference(T referent, ReferenceQueue<? super T> queue) {
 370         this.referent = referent;
 371         this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
 372     }
 373 
 374     /**
 375      * Ensures that the object referenced by the given reference remains
 376      * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
 377      * regardless of any prior actions of the program that might otherwise cause
 378      * the object to become unreachable; thus, the referenced object is not
 379      * reclaimable by garbage collection at least until after the invocation of
 380      * this method.  Invocation of this method does not itself initiate garbage
 381      * collection or finalization.
 382      *
 383      * <p> This method establishes an ordering for
 384      * <a href="package-summary.html#reachability"><em>strong reachability</em></a>
 385      * with respect to garbage collection.  It controls relations that are
 386      * otherwise only implicit in a program -- the reachability conditions
 387      * triggering garbage collection.  This method is designed for use in
 388      * uncommon situations of premature finalization where using
 389      * {@code synchronized} blocks or methods, or using other synchronization
 390      * facilities are not possible or do not provide the desired control.  This
 391      * method is applicable only when reclamation may have visible effects,
 392      * which is possible for objects with finalizers (See
 393      * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6">
 394      * Section 12.6 17 of <cite>The Java&trade; Language Specification</cite></a>)
 395      * that are implemented in ways that rely on ordering control for correctness.
 396      *
 397      * @apiNote
 398      * Finalization may occur whenever the virtual machine detects that no
 399      * reference to an object will ever be stored in the heap: The garbage
 400      * collector may reclaim an object even if the fields of that object are
 401      * still in use, so long as the object has otherwise become unreachable.
 402      * This may have surprising and undesirable effects in cases such as the
 403      * following example in which the bookkeeping associated with a class is
 404      * managed through array indices.  Here, method {@code action} uses a
 405      * {@code reachabilityFence} to ensure that the {@code Resource} object is
 406      * not reclaimed before bookkeeping on an associated
 407      * {@code ExternalResource} has been performed; in particular here, to
 408      * ensure that the array slot holding the {@code ExternalResource} is not
 409      * nulled out in method {@link Object#finalize}, which may otherwise run
 410      * concurrently.
 411      *
 412      * <pre> {@code
 413      * class Resource {
 414      *   private static ExternalResource[] externalResourceArray = ...
 415      *
 416      *   int myIndex;
 417      *   Resource(...) {
 418      *     myIndex = ...
 419      *     externalResourceArray[myIndex] = ...;
 420      *     ...
 421      *   }
 422      *   protected void finalize() {
 423      *     externalResourceArray[myIndex] = null;
 424      *     ...
 425      *   }
 426      *   public void action() {
 427      *     try {
 428      *       // ...
 429      *       int i = myIndex;
 430      *       Resource.update(externalResourceArray[i]);
 431      *     } finally {
 432      *       Reference.reachabilityFence(this);
 433      *     }
 434      *   }
 435      *   private static void update(ExternalResource ext) {
 436      *     ext.status = ...;
 437      *   }
 438      * }}</pre>
 439      *
 440      * Here, the invocation of {@code reachabilityFence} is nonintuitively
 441      * placed <em>after</em> the call to {@code update}, to ensure that the
 442      * array slot is not nulled out by {@link Object#finalize} before the
 443      * update, even if the call to {@code action} was the last use of this
 444      * object.  This might be the case if, for example a usage in a user program
 445      * had the form {@code new Resource().action();} which retains no other
 446      * reference to this {@code Resource}.  While probably overkill here,
 447      * {@code reachabilityFence} is placed in a {@code finally} block to ensure
 448      * that it is invoked across all paths in the method.  In a method with more
 449      * complex control paths, you might need further precautions to ensure that
 450      * {@code reachabilityFence} is encountered along all of them.
 451      *
 452      * <p> It is sometimes possible to better encapsulate use of
 453      * {@code reachabilityFence}.  Continuing the above example, if it were
 454      * acceptable for the call to method {@code update} to proceed even if the
 455      * finalizer had already executed (nulling out slot), then you could
 456      * localize use of {@code reachabilityFence}:
 457      *
 458      * <pre> {@code
 459      * public void action2() {
 460      *   // ...
 461      *   Resource.update(getExternalResource());
 462      * }
 463      * private ExternalResource getExternalResource() {
 464      *   ExternalResource ext = externalResourceArray[myIndex];
 465      *   Reference.reachabilityFence(this);
 466      *   return ext;
 467      * }}</pre>
 468      *
 469      * <p> Method {@code reachabilityFence} is not required in constructions
 470      * that themselves ensure reachability.  For example, because objects that
 471      * are locked cannot, in general, be reclaimed, it would suffice if all
 472      * accesses of the object, in all methods of class {@code Resource}
 473      * (including {@code finalize}) were enclosed in {@code synchronized (this)}
 474      * blocks.  (Further, such blocks must not include infinite loops, or
 475      * themselves be unreachable, which fall into the corner case exceptions to
 476      * the "in general" disclaimer.)  However, method {@code reachabilityFence}
 477      * remains a better option in cases where this approach is not as efficient,
 478      * desirable, or possible; for example because it would encounter deadlock.
 479      *
 480      * @param ref the reference. If {@code null}, this method has no effect.
 481      * @since 9
 482      */
 483     @ForceInline
 484     public static void reachabilityFence(Object ref) {
 485         // Does nothing. This method is annotated with @ForceInline to eliminate
 486         // most of the overhead that using @DontInline would cause with the
 487         // HotSpot JVM, when this fence is used in a wide variety of situations.
 488         // HotSpot JVM retains the ref and does not GC it before a call to
 489         // this method, because the JIT-compilers do not have GC-only safepoints.
 490     }
 491 }