< 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


 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();




  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


 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             Thread.yield();
 197             // retry
 198             return true;
 199         } catch (InterruptedException x) {
 200             // retry






 201             return true;
 202         }
 203 
 204         ReferenceQueue<? super Object> q = r.queue;
 205         if (q != ReferenceQueue.NULL) q.enqueue(r);
 206         return true;
 207     }
 208 
 209     static {
 210         ThreadGroup tg = Thread.currentThread().getThreadGroup();
 211         for (ThreadGroup tgn = tg;
 212              tgn != null;
 213              tg = tgn, tgn = tg.getParent());
 214         Thread handler = new ReferenceHandler(tg, "Reference Handler");
 215         /* If there were a special system-only priority greater than
 216          * MAX_PRIORITY, it would be used here
 217          */
 218         handler.setPriority(Thread.MAX_PRIORITY);
 219         handler.setDaemon(true);
 220         handler.start();


< prev index next >