< prev index next >

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

Print this page




  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     /**




  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


  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     /* 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                 Reference<?> p = getPendingReferences();
 154                 enqueuePendingReferences(p);
 155             }
 156         }
 157     }
 158 
 159     /**
 160      * Blocks until GC discovers some pending references and hands them to us.
 161      *
 162      * @return a list of pending references linked via {@link #discovered} field
 163      * with {@code null} marking the end of list.
 164      */
 165     static Reference<?> getPendingReferences() {
 166         Reference<?> p;












 167         synchronized (lock) {
 168             while ((p = pending) == null) {
 169                 try {










 170                     lock.wait();





 171                 } catch (OutOfMemoryError x) {
 172                     // The waiting on the lock may cause an OutOfMemoryError
 173                     // because it may try to allocate InterruptedException object.
 174                     // Give other threads CPU time so they hopefully drop some live
 175                     // references and GC reclaims some space.
 176                     Thread.yield();


 177                 } catch (InterruptedException x) {
 178                     // ignore interrupts

 179                 }
 180             }
 181             pending = null;
 182         }
 183         return p;

 184     }
 185 
 186     /**
 187      * Enqueue a list of pending {@link Reference}s.
 188      *
 189      * @param p a list of pending references linked via {@link #discovered}
 190      *          field with {@code null} marking the end of list
 191      */
 192     static void enqueuePendingReferences(Reference<?> p) {
 193         while (p != null) {
 194             Reference<?> r = p;
 195             p = r.discovered;
 196             r.discovered = null;
 197             @SuppressWarnings("unchecked")
 198             ReferenceQueue<Object> q = (ReferenceQueue) r.queue;
 199             if (q != ReferenceQueue.NULL) q.enqueue(r);
 200         }
 201     }
 202 
 203     static {
 204         ThreadGroup tg = Thread.currentThread().getThreadGroup();
 205         for (ThreadGroup tgn = tg;
 206              tgn != null;
 207              tg = tgn, tgn = tg.getParent());
 208         Thread handler = new ReferenceHandler(tg, "Reference Handler");
 209         /* If there were a special system-only priority greater than
 210          * MAX_PRIORITY, it would be used here
 211          */
 212         handler.setPriority(Thread.MAX_PRIORITY);
 213         handler.setDaemon(true);
 214         handler.start();
 215 
 216         // provide access in SharedSecrets
 217         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
 218 
 219             @Override
 220             public boolean cleanNextEnqueuedCleanable(Cleaner cleaner) {
 221                 return cleaner.cleanNextEnqueued();
 222             }
 223         });
 224     }
 225 
 226     /* -- Referent accessor and setters -- */
 227 
 228     /**
 229      * Returns this reference object's referent.  If this reference object has
 230      * been cleared, either by the program or by the garbage collector, then
 231      * this method returns <code>null</code>.
 232      *
 233      * @return   The object to which this reference refers, or
 234      *           <code>null</code> if this reference object has been cleared
 235      */
 236     @HotSpotIntrinsicCandidate
 237     public T get() {
 238         return this.referent;
 239     }
 240 
 241     /**


< prev index next >