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