< prev index next >

src/java.base/share/classes/java/lang/ref/Reference.java

Print this page




   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


  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     /* Object used to synchronize with the garbage collector.  The collector
 114      * must acquire this lock at the beginning of each collection cycle.  It is
 115      * therefore critical that any code holding this lock complete as quickly
 116      * as possible, allocate no new objects, and avoid calling user code.
 117      */
 118     private static class Lock { }
 119     private static Lock lock = new Lock();
 120 
 121 
 122     /* List of References waiting to be enqueued.  The collector adds
 123      * References to this list, while the Reference-handler thread removes
 124      * them.  This list is protected by the above lock object. The
 125      * list uses the discovered field to link its elements.
 126      */
 127     private static Reference<Object> pending = null;









 128 
 129     /* High-priority thread to enqueue pending References
 130      */
 131     private static class ReferenceHandler extends Thread {
 132 
 133         private static void ensureClassInitialized(Class<?> clazz) {
 134             try {
 135                 Class.forName(clazz.getName(), true, clazz.getClassLoader());
 136             } catch (ClassNotFoundException e) {
 137                 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
 138             }
 139         }
 140 
 141         static {
 142             // pre-load and initialize InterruptedException and Cleaner classes
 143             // so that we don't get into trouble later in the run loop if there's
 144             // memory shortage while loading/initializing them lazily.
 145             ensureClassInitialized(InterruptedException.class);
 146             ensureClassInitialized(Cleaner.class);
 147         }
 148 
 149         ReferenceHandler(ThreadGroup g, String name) {
 150             super(g, null, name, 0, false);
 151         }
 152 
 153         public void run() {

 154             while (true) {
 155                 tryHandlePending(true);

 156             }
 157         }
 158     }
 159 
 160     /**
 161      * Try handle pending {@link Reference} if there is one.<p>
 162      * Return {@code true} as a hint that there might be another
 163      * {@link Reference} pending or {@code false} when there are no more pending
 164      * {@link Reference}s at the moment and the program can do some other
 165      * useful work instead of looping.
 166      *
 167      * @param waitForNotify if {@code true} and there was no pending
 168      *                      {@link Reference}, wait until notified from VM
 169      *                      or interrupted; if {@code false}, return immediately
 170      *                      when there is no pending {@link Reference}.
 171      * @return {@code true} if there was a {@link Reference} pending and it
 172      *         was processed, or we waited for notification and either got it
 173      *         or thread was interrupted before being notified;
 174      *         {@code false} otherwise.
 175      */
 176     static boolean tryHandlePending(boolean waitForNotify) {
 177         Reference<Object> r;
 178         Cleaner c;
 179         try {
 180             synchronized (lock) {
 181                 if (pending != null) {
 182                     r = pending;
 183                     // 'instanceof' might throw OutOfMemoryError sometimes
 184                     // so do this before un-linking 'r' from the 'pending' chain...
 185                     c = r instanceof Cleaner ? (Cleaner) r : null;
 186                     // unlink 'r' from 'pending' chain
 187                     pending = r.discovered;
 188                     r.discovered = null;
 189                 } else {
 190                     // The waiting on the lock may cause an OutOfMemoryError
 191                     // because it may try to allocate exception objects.
 192                     if (waitForNotify) {
 193                         lock.wait();
 194                     }
 195                     // retry if waited
 196                     return waitForNotify;
 197                 }
 198             }
 199         } catch (OutOfMemoryError x) {
 200             // Give other threads CPU time so they hopefully drop some live references
 201             // and GC reclaims some space.
 202             // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above
 203             // persistently throws OOME for some time...
 204             Thread.yield();
 205             // retry
 206             return true;
 207         } catch (InterruptedException x) {
 208             // retry
 209             return true;






 210         }
 211 
 212         // Fast path for cleaners
 213         if (c != null) {
 214             c.clean();
 215             return true;





 216         }
 217 
 218         ReferenceQueue<? super Object> q = r.queue;




















 219         if (q != ReferenceQueue.NULL) q.enqueue(r);
 220         return true;





































 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 tryHandlePendingReference() {
 240                 return tryHandlePending(false);






 241             }
 242         });
 243     }
 244 
 245     /* -- Referent accessor and setters -- */
 246 
 247     /**
 248      * Returns this reference object's referent.  If this reference object has
 249      * been cleared, either by the program or by the garbage collector, then
 250      * this method returns <code>null</code>.
 251      *
 252      * @return   The object to which this reference refers, or
 253      *           <code>null</code> if this reference object has been cleared
 254      */
 255     @HotSpotIntrinsicCandidate
 256     public T get() {
 257         return this.referent;
 258     }
 259 
 260     /**




   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.HotSpotIntrinsicCandidate;
  29 import jdk.internal.misc.JavaLangRefAccess;
  30 import jdk.internal.misc.SharedSecrets;
  31 import jdk.internal.vm.annotation.DontInline;
  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


  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<?> 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 final 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<?> pending;
 127 
 128     /* Discovery phase counter, guarder by above lock.
 129      */
 130     private static int discoveryPhase;
 131 
 132     /* Enqueue phase, guarded by enqueuePhaseLock object.
 133      */
 134     private static int enqueuePhase;
 135     private static final Object enqueuePhaseLock = new Object();
 136 
 137     /* High-priority thread to enqueue pending References
 138      */
 139     private static class ReferenceHandler extends Thread {
 140 
 141         private static void ensureClassInitialized(Class<?> clazz) {
 142             try {
 143                 Class.forName(clazz.getName(), true, clazz.getClassLoader());
 144             } catch (ClassNotFoundException e) {
 145                 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
 146             }
 147         }
 148 
 149         static {
 150             // pre-load and initialize InterruptedException class
 151             // so that we don't get into trouble later in the run loop if there's
 152             // memory shortage while loading/initializing it lazily.
 153             ensureClassInitialized(InterruptedException.class);

 154         }
 155 
 156         ReferenceHandler(ThreadGroup g, String name) {
 157             super(g, null, name, 0, false);
 158         }
 159 
 160         public void run() {
 161             int[] discoveryPhase = new int[1];
 162             while (true) {
 163                 Reference<?> p = getPendingReferences(discoveryPhase);
 164                 enqueuePendingReferences(p, discoveryPhase[0]);
 165             }
 166         }
 167     }
 168 
 169     /**
 170      * Blocks until GC discovers some pending references, sets the 0-th element
 171      * of given {@code discoveryPhaseHolder} to the phase in which they were
 172      * discovered and returns the head of the list of discovered references.
 173      *
 174      * @param discoveryPhaseHolder a 1-element array to hold the returned
 175      *                             discovery phase.
 176      * @return the head of a list of pending references linked via
 177      * {@link #discovered} field with {@code null} marking the end of list.
 178      */
 179     static Reference<?> getPendingReferences(int[] discoveryPhaseHolder) {
 180         Reference<?> p;








 181         synchronized (lock) {
 182             while ((p = pending) == null) {
 183                 try {










 184                     lock.wait();





 185                 } catch (OutOfMemoryError x) {
 186                     // The waiting on the lock may cause an OutOfMemoryError
 187                     // because it may try to allocate InterruptedException object.
 188                     // Give other threads CPU time so they hopefully drop some live
 189                     // references and GC reclaims some space.
 190                     Thread.yield();


 191                 } catch (InterruptedException x) {
 192                     // ignore interrupts
 193                 }
 194             }
 195             pending = null;
 196             // increment discoveryPhase counter and return it in a holder array
 197             discoveryPhaseHolder[0] = ++discoveryPhase;
 198         }
 199         return p;
 200     }
 201 
 202     /**
 203      * @return current finished discovery phase.
 204      */
 205     static int getDiscoveryPhase() {
 206         synchronized (lock) {
 207             return (pending == null)
 208                    ? discoveryPhase      // already incremented
 209                    : discoveryPhase + 1; // not yet incremented
 210         }
 211     }
 212 
 213     /**
 214      * Enqueue a list of pending {@link Reference}s linked via {@link #discovered}
 215      * field with {@code null} marking the end of list.
 216      * <p>
 217      * The {@link #enqueuePhase} is set to given {@code discoveryPhase}
 218      * after all references from the list have been enqueued and any waiters on
 219      * {@link #enqueuePhaseLock} are notified.
 220      *
 221      * @param p a list of pending references linked via {@link #discovered}
 222      *          field with {@code null} marking the end of list.
 223      * @param discoveryPhase the phase in which given references were discovered.
 224      */
 225     static void enqueuePendingReferences(Reference<?> p, int discoveryPhase) {
 226         try {
 227             // distribute unhooked pending references to their respective queues
 228             while (p != null) {
 229                 Reference<?> r = p;
 230                 p = r.discovered;
 231                 r.discovered = null;
 232                 @SuppressWarnings("unchecked")
 233                 ReferenceQueue<Object> q = (ReferenceQueue) r.queue;
 234                 if (q != ReferenceQueue.NULL) q.enqueue(r);
 235             }
 236         } finally {
 237             // mark the enqueueing of references discovered in given
 238             // discovery phase is finished and notify waiters.
 239             synchronized (enqueuePhaseLock) {
 240                 enqueuePhase = discoveryPhase;
 241                 enqueuePhaseLock.notifyAll();
 242             }
 243         }
 244     }
 245 
 246     /**
 247      * Triggers discovery of new Reference(s) and returns the phase sequence number
 248      * in which they were discovered or previous phase sequence number if no new
 249      * Reference(s) were discovered.
 250      */
 251     static int discoverReferences() {
 252         // trigger discovery of new Reference(s)
 253         System.gc();
 254         // obtain the phase in which they were discovered (if any)
 255         return getDiscoveryPhase();
 256     }
 257 
 258     /**
 259      * Blocks until all Reference(s) that were discovered in given
 260      * {@code discoveryPhase} (as returned by {@link #discoverReferences()})
 261      * have been enqueued.
 262      *
 263      * @param discoveryPhase the discovery phase sequence number.
 264      * @throws InterruptedException if interrupted while waiting.
 265      */
 266     static void awaitReferencesEnqueued(int discoveryPhase) throws InterruptedException {
 267         // await for them to be enqueued
 268         synchronized (enqueuePhaseLock) {
 269             while (enqueuePhase - discoveryPhase < 0) {
 270                 enqueuePhaseLock.wait();
 271             }
 272         }
 273     }
 274 
 275     static {
 276         ThreadGroup tg = Thread.currentThread().getThreadGroup();
 277         for (ThreadGroup tgn = tg;
 278              tgn != null;
 279              tg = tgn, tgn = tg.getParent());
 280         Thread handler = new ReferenceHandler(tg, "Reference Handler");
 281         /* If there were a special system-only priority greater than
 282          * MAX_PRIORITY, it would be used here
 283          */
 284         handler.setPriority(Thread.MAX_PRIORITY);
 285         handler.setDaemon(true);
 286         handler.start();
 287 
 288         // provide access in SharedSecrets
 289         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
 290             @Override
 291             public int discoverReferences() {
 292                 return Reference.discoverReferences();
 293             }
 294 
 295             @Override
 296             public void awaitReferencesEnqueued(
 297                 int discoveryPhase) throws InterruptedException {
 298                 Reference.awaitReferencesEnqueued(discoveryPhase);
 299             }
 300         });
 301     }
 302 
 303     /* -- Referent accessor and setters -- */
 304 
 305     /**
 306      * Returns this reference object's referent.  If this reference object has
 307      * been cleared, either by the program or by the garbage collector, then
 308      * this method returns <code>null</code>.
 309      *
 310      * @return   The object to which this reference refers, or
 311      *           <code>null</code> if this reference object has been cleared
 312      */
 313     @HotSpotIntrinsicCandidate
 314     public T get() {
 315         return this.referent;
 316     }
 317 
 318     /**


< prev index next >