1 /*
   2  * Copyright (c) 1997, 2017, 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.DontInline;
  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      * system property to disable clearing before enqueuing.
 145      */
 146     private static final boolean disableClearBeforeEnqueue
 147         = Boolean.getBoolean("jdk.ref.disableClearBeforeEnqueue");
 148 
 149     /*
 150      * Atomically get and clear (set to null) the VM's pending list.
 151      */
 152     private static native Reference<Object> getAndClearReferencePendingList();
 153 
 154     /*
 155      * Test whether the VM's pending list contains any entries.
 156      */
 157     private static native boolean hasReferencePendingList();
 158 
 159     /*
 160      * Wait until the VM's pending list may be non-null.
 161      */
 162     private static native void waitForReferencePendingList();
 163 
 164     private static final Object processPendingLock = new Object();
 165     private static boolean processPendingActive = false;
 166 
 167     private static void processPendingReferences() {
 168         // Only the singleton reference processing thread calls
 169         // waitForReferencePendingList() and getAndClearReferencePendingList().
 170         // These are separate operations to avoid a race with other threads
 171         // that are calling waitForReferenceProcessing().
 172         waitForReferencePendingList();
 173         Reference<Object> pendingList;
 174         synchronized (processPendingLock) {
 175             pendingList = getAndClearReferencePendingList();
 176             processPendingActive = true;
 177         }
 178         while (pendingList != null) {
 179             Reference<Object> ref = pendingList;
 180             pendingList = ref.discovered;
 181             ref.discovered = null;
 182 
 183             if (ref instanceof Cleaner) {
 184                 ((Cleaner)ref).clean();
 185                 // Notify any waiters that progress has been made.
 186                 // This improves latency for nio.Bits waiters, which
 187                 // are the only important ones.
 188                 synchronized (processPendingLock) {
 189                     processPendingLock.notifyAll();
 190                 }
 191             } else {
 192                 ReferenceQueue<? super Object> q = ref.queue;
 193                 if (q != ReferenceQueue.NULL) q.enqueue(ref);
 194             }
 195         }
 196         // Notify any waiters of completion of current round.
 197         synchronized (processPendingLock) {
 198             processPendingActive = false;
 199             processPendingLock.notifyAll();
 200         }
 201     }
 202 
 203     // Wait for progress in reference processing.
 204     //
 205     // Returns true after waiting (for notification from the reference
 206     // processing thread) if either (1) the VM has any pending
 207     // references, or (2) the reference processing thread is
 208     // processing references. Otherwise, returns false immediately.
 209     private static boolean waitForReferenceProcessing()
 210         throws InterruptedException
 211     {
 212         synchronized (processPendingLock) {
 213             if (processPendingActive || hasReferencePendingList()) {
 214                 // Wait for progress, not necessarily completion.
 215                 processPendingLock.wait();
 216                 return true;
 217             } else {
 218                 return false;
 219             }
 220         }
 221     }
 222 
 223     static {
 224         ThreadGroup tg = Thread.currentThread().getThreadGroup();
 225         for (ThreadGroup tgn = tg;
 226              tgn != null;
 227              tg = tgn, tgn = tg.getParent());
 228         Thread handler = new ReferenceHandler(tg, "Reference Handler");
 229         /* If there were a special system-only priority greater than
 230          * MAX_PRIORITY, it would be used here
 231          */
 232         handler.setPriority(Thread.MAX_PRIORITY);
 233         handler.setDaemon(true);
 234         handler.start();
 235 
 236         // provide access in SharedSecrets
 237         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
 238             @Override
 239             public boolean waitForReferenceProcessing()
 240                 throws InterruptedException
 241             {
 242                 return Reference.waitForReferenceProcessing();
 243             }
 244         });
 245     }
 246 
 247     /* -- Referent accessor and setters -- */
 248 
 249     /**
 250      * Returns this reference object's referent.  If this reference object has
 251      * been cleared, either by the program or by the garbage collector, then
 252      * this method returns <code>null</code>.
 253      *
 254      * @return   The object to which this reference refers, or
 255      *           <code>null</code> if this reference object has been cleared
 256      */
 257     @HotSpotIntrinsicCandidate
 258     public T get() {
 259         return this.referent;
 260     }
 261 
 262     /**
 263      * Clears this reference object.  Invoking this method will not cause this
 264      * object to be enqueued.
 265      *
 266      * <p> This method is invoked only by Java code; when the garbage collector
 267      * clears references it does so directly, without invoking this method.
 268      */
 269     public void clear() {
 270         this.referent = null;
 271     }
 272 
 273     /* -- Queue operations -- */
 274 
 275     /**
 276      * Tells whether or not this reference object has been enqueued, either by
 277      * the program or by the garbage collector.  If this reference object was
 278      * not registered with a queue when it was created, then this method will
 279      * always return <code>false</code>.
 280      *
 281      * @return   <code>true</code> if and only if this reference object has
 282      *           been enqueued
 283      */
 284     public boolean isEnqueued() {
 285         return (this.queue == ReferenceQueue.ENQUEUED);
 286     }
 287 
 288     /**
 289      * Clears this reference object and adds it to the queue with which
 290      * it is registered, if any.
 291      *
 292      * <p> This method is invoked only by Java code; when the garbage collector
 293      * enqueues references it does so directly, without invoking this method.
 294      *
 295      * @return   <code>true</code> if this reference object was successfully
 296      *           enqueued; <code>false</code> if it was already enqueued or if
 297      *           it was not registered with a queue when it was created
 298      */
 299     public boolean enqueue() {
 300         if (!disableClearBeforeEnqueue)
 301             this.referent = null;
 302         return this.queue.enqueue(this);
 303     }
 304 
 305     /* -- Constructors -- */
 306 
 307     Reference(T referent) {
 308         this(referent, null);
 309     }
 310 
 311     Reference(T referent, ReferenceQueue<? super T> queue) {
 312         this.referent = referent;
 313         this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
 314     }
 315 
 316     /**
 317      * Ensures that the object referenced by the given reference remains
 318      * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
 319      * regardless of any prior actions of the program that might otherwise cause
 320      * the object to become unreachable; thus, the referenced object is not
 321      * reclaimable by garbage collection at least until after the invocation of
 322      * this method.  Invocation of this method does not itself initiate garbage
 323      * collection or finalization.
 324      *
 325      * <p> This method establishes an ordering for
 326      * <a href="package-summary.html#reachability"><em>strong reachability</em></a>
 327      * with respect to garbage collection.  It controls relations that are
 328      * otherwise only implicit in a program -- the reachability conditions
 329      * triggering garbage collection.  This method is designed for use in
 330      * uncommon situations of premature finalization where using
 331      * {@code synchronized} blocks or methods, or using other synchronization
 332      * facilities are not possible or do not provide the desired control.  This
 333      * method is applicable only when reclamation may have visible effects,
 334      * which is possible for objects with finalizers (See
 335      * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6">
 336      * Section 12.6 17 of <cite>The Java&trade; Language Specification</cite></a>)
 337      * that are implemented in ways that rely on ordering control for correctness.
 338      *
 339      * @apiNote
 340      * Finalization may occur whenever the virtual machine detects that no
 341      * reference to an object will ever be stored in the heap: The garbage
 342      * collector may reclaim an object even if the fields of that object are
 343      * still in use, so long as the object has otherwise become unreachable.
 344      * This may have surprising and undesirable effects in cases such as the
 345      * following example in which the bookkeeping associated with a class is
 346      * managed through array indices.  Here, method {@code action} uses a
 347      * {@code reachabilityFence} to ensure that the {@code Resource} object is
 348      * not reclaimed before bookkeeping on an associated
 349      * {@code ExternalResource} has been performed; in particular here, to
 350      * ensure that the array slot holding the {@code ExternalResource} is not
 351      * nulled out in method {@link Object#finalize}, which may otherwise run
 352      * concurrently.
 353      *
 354      * <pre> {@code
 355      * class Resource {
 356      *   private static ExternalResource[] externalResourceArray = ...
 357      *
 358      *   int myIndex;
 359      *   Resource(...) {
 360      *     myIndex = ...
 361      *     externalResourceArray[myIndex] = ...;
 362      *     ...
 363      *   }
 364      *   protected void finalize() {
 365      *     externalResourceArray[myIndex] = null;
 366      *     ...
 367      *   }
 368      *   public void action() {
 369      *     try {
 370      *       // ...
 371      *       int i = myIndex;
 372      *       Resource.update(externalResourceArray[i]);
 373      *     } finally {
 374      *       Reference.reachabilityFence(this);
 375      *     }
 376      *   }
 377      *   private static void update(ExternalResource ext) {
 378      *     ext.status = ...;
 379      *   }
 380      * }}</pre>
 381      *
 382      * Here, the invocation of {@code reachabilityFence} is nonintuitively
 383      * placed <em>after</em> the call to {@code update}, to ensure that the
 384      * array slot is not nulled out by {@link Object#finalize} before the
 385      * update, even if the call to {@code action} was the last use of this
 386      * object.  This might be the case if, for example a usage in a user program
 387      * had the form {@code new Resource().action();} which retains no other
 388      * reference to this {@code Resource}.  While probably overkill here,
 389      * {@code reachabilityFence} is placed in a {@code finally} block to ensure
 390      * that it is invoked across all paths in the method.  In a method with more
 391      * complex control paths, you might need further precautions to ensure that
 392      * {@code reachabilityFence} is encountered along all of them.
 393      *
 394      * <p> It is sometimes possible to better encapsulate use of
 395      * {@code reachabilityFence}.  Continuing the above example, if it were
 396      * acceptable for the call to method {@code update} to proceed even if the
 397      * finalizer had already executed (nulling out slot), then you could
 398      * localize use of {@code reachabilityFence}:
 399      *
 400      * <pre> {@code
 401      * public void action2() {
 402      *   // ...
 403      *   Resource.update(getExternalResource());
 404      * }
 405      * private ExternalResource getExternalResource() {
 406      *   ExternalResource ext = externalResourceArray[myIndex];
 407      *   Reference.reachabilityFence(this);
 408      *   return ext;
 409      * }}</pre>
 410      *
 411      * <p> Method {@code reachabilityFence} is not required in constructions
 412      * that themselves ensure reachability.  For example, because objects that
 413      * are locked cannot, in general, be reclaimed, it would suffice if all
 414      * accesses of the object, in all methods of class {@code Resource}
 415      * (including {@code finalize}) were enclosed in {@code synchronized (this)}
 416      * blocks.  (Further, such blocks must not include infinite loops, or
 417      * themselves be unreachable, which fall into the corner case exceptions to
 418      * the "in general" disclaimer.)  However, method {@code reachabilityFence}
 419      * remains a better option in cases where this approach is not as efficient,
 420      * desirable, or possible; for example because it would encounter deadlock.
 421      *
 422      * @param ref the reference. If {@code null}, this method has no effect.
 423      * @since 9
 424      */
 425     @DontInline
 426     public static void reachabilityFence(Object ref) {
 427         // Does nothing, because this method is annotated with @DontInline
 428         // HotSpot needs to retain the ref and not GC it before a call to this
 429         // method
 430     }
 431 }