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