< prev index next >

src/java.base/share/classes/java/lang/Thread.java

Print this page




  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;
  27 
  28 import java.lang.ref.Reference;
  29 import java.lang.ref.ReferenceQueue;
  30 import java.lang.ref.WeakReference;
  31 import java.security.AccessController;
  32 import java.security.AccessControlContext;
  33 import java.security.PrivilegedAction;
  34 import java.util.Map;
  35 import java.util.HashMap;
  36 import java.util.concurrent.ConcurrentHashMap;
  37 import java.util.concurrent.ConcurrentMap;
  38 import java.util.concurrent.TimeUnit;
  39 import java.util.concurrent.locks.LockSupport;
  40 

  41 import jdk.internal.misc.TerminatingThreadLocal;
  42 import sun.nio.ch.Interruptible;
  43 import jdk.internal.reflect.CallerSensitive;
  44 import jdk.internal.reflect.Reflection;
  45 import sun.security.util.SecurityConstants;
  46 import jdk.internal.HotSpotIntrinsicCandidate;
  47 
  48 /**
  49  * A <i>thread</i> is a thread of execution in a program. The Java
  50  * Virtual Machine allows an application to have multiple threads of
  51  * execution running concurrently.
  52  * <p>
  53  * Every thread has a priority. Threads with higher priority are
  54  * executed in preference to threads with lower priority. Each thread
  55  * may or may not also be marked as a daemon. When code running in
  56  * some thread creates a new {@code Thread} object, the new
  57  * thread has its priority initially set equal to the priority of the
  58  * creating thread, and is a daemon thread if and only if the
  59  * creating thread is a daemon.
  60  * <p>


 181     ThreadLocal.ThreadLocalMap threadLocals = null;
 182 
 183     /*
 184      * InheritableThreadLocal values pertaining to this thread. This map is
 185      * maintained by the InheritableThreadLocal class.
 186      */
 187     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
 188 
 189     /*
 190      * The requested stack size for this thread, or 0 if the creator did
 191      * not specify a stack size.  It is up to the VM to do whatever it
 192      * likes with this number; some VMs will ignore it.
 193      */
 194     private final long stackSize;
 195 
 196     /*
 197      * Thread ID
 198      */
 199     private final long tid;
 200 





 201     /* For generating thread ID */
 202     private static long threadSeqNumber;
 203 
 204     private static synchronized long nextThreadID() {
 205         return ++threadSeqNumber;
 206     }
 207 
 208     /*
 209      * Java thread status for tools, default indicates thread 'not yet started'
 210      */
 211     private volatile int threadStatus;
 212 
 213     /**
 214      * The argument supplied to the current call to
 215      * java.util.concurrent.locks.LockSupport.park.
 216      * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
 217      * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
 218      */
 219     volatile Object parkBlocker;
 220 
 221     /* The object in which this thread is blocked in an interruptible I/O
 222      * operation, if any.  The blocker's interrupt method should be invoked
 223      * after setting this thread's interrupt status.
 224      */
 225     private volatile Interruptible blocker;
 226     private final Object blockerLock = new Object();
 227 
 228     /* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
 229      * from java.nio code
 230      */
 231     static void blockedOn(Interruptible b) {
 232         Thread me = Thread.currentThread();
 233         synchronized (me.blockerLock) {
 234             me.blocker = b;
 235         }
 236     }
 237 












 238     /**
 239      * The minimum priority that a thread can have.
 240      */
 241     public static final int MIN_PRIORITY = 1;
 242 
 243    /**
 244      * The default priority that is assigned to a thread.
 245      */
 246     public static final int NORM_PRIORITY = 5;
 247 
 248     /**
 249      * The maximum priority that a thread can have.
 250      */
 251     public static final int MAX_PRIORITY = 10;
 252 
 253     /**
 254      * Returns a reference to the currently executing thread object.
 255      *
 256      * @return  the currently executing thread.



















 257      */




 258     @HotSpotIntrinsicCandidate
 259     public static native Thread currentThread();






























 260 
 261     /**
 262      * A hint to the scheduler that the current thread is willing to yield
 263      * its current use of a processor. The scheduler is free to ignore this
 264      * hint.
 265      *
 266      * <p> Yield is a heuristic attempt to improve relative progression
 267      * between threads that would otherwise over-utilise a CPU. Its use
 268      * should be combined with detailed profiling and benchmarking to
 269      * ensure that it actually has the desired effect.
 270      *
 271      * <p> It is rarely appropriate to use this method. It may be useful
 272      * for debugging or testing purposes, where it may help to reproduce
 273      * bugs due to race conditions. It may also be useful when designing
 274      * concurrency control constructs such as the ones in the
 275      * {@link java.util.concurrent.locks} package.
 276      */
 277     public static native void yield();








 278 
 279     /**
 280      * Causes the currently executing thread to sleep (temporarily cease
 281      * execution) for the specified number of milliseconds, subject to
 282      * the precision and accuracy of system timers and schedulers. The thread
 283      * does not lose ownership of any monitors.
 284      *
 285      * @param  millis
 286      *         the length of time to sleep in milliseconds
 287      *
 288      * @throws  IllegalArgumentException
 289      *          if the value of {@code millis} is negative
 290      *
 291      * @throws  InterruptedException
 292      *          if any thread has interrupted the current thread. The
 293      *          <i>interrupted status</i> of the current thread is
 294      *          cleared when this exception is thrown.
 295      */
 296     public static native void sleep(long millis) throws InterruptedException;










 297 
 298     /**
 299      * Causes the currently executing thread to sleep (temporarily cease
 300      * execution) for the specified number of milliseconds plus the specified
 301      * number of nanoseconds, subject to the precision and accuracy of system
 302      * timers and schedulers. The thread does not lose ownership of any
 303      * monitors.
 304      *
 305      * @param  millis
 306      *         the length of time to sleep in milliseconds
 307      *
 308      * @param  nanos
 309      *         {@code 0-999999} additional nanoseconds to sleep
 310      *
 311      * @throws  IllegalArgumentException
 312      *          if the value of {@code millis} is negative, or the value of
 313      *          {@code nanos} is not in the range {@code 0-999999}
 314      *
 315      * @throws  InterruptedException
 316      *          if any thread has interrupted the current thread. The
 317      *          <i>interrupted status</i> of the current thread is
 318      *          cleared when this exception is thrown.
 319      */
 320     public static void sleep(long millis, int nanos)
 321     throws InterruptedException {
 322         if (millis < 0) {
 323             throw new IllegalArgumentException("timeout value is negative");
 324         }
 325 
 326         if (nanos < 0 || nanos > 999999) {
 327             throw new IllegalArgumentException(
 328                                 "nanosecond timeout value out of range");
 329         }
 330 
 331         if (nanos > 0 && millis < Long.MAX_VALUE) {
 332             millis++;
 333         }
 334 
 335         sleep(millis);
 336     }
 337 
 338     /**
 339      * Indicates that the caller is momentarily unable to progress, until the
 340      * occurrence of one or more actions on the part of other activities. By
 341      * invoking this method within each iteration of a spin-wait loop construct,


 435         this.priority = parent.getPriority();
 436         if (security == null || isCCLOverridden(parent.getClass()))
 437             this.contextClassLoader = parent.getContextClassLoader();
 438         else
 439             this.contextClassLoader = parent.contextClassLoader;
 440         this.inheritedAccessControlContext =
 441                 acc != null ? acc : AccessController.getContext();
 442         this.target = target;
 443         setPriority(priority);
 444         if (inheritThreadLocals && parent.inheritableThreadLocals != null)
 445             this.inheritableThreadLocals =
 446                 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
 447         /* Stash the specified stack size in case the VM cares */
 448         this.stackSize = stackSize;
 449 
 450         /* Set thread ID */
 451         this.tid = nextThreadID();
 452     }
 453 
 454     /**
























 455      * Throws CloneNotSupportedException as a Thread can not be meaningfully
 456      * cloned. Construct a new Thread instead.
 457      *
 458      * @throws  CloneNotSupportedException
 459      *          always
 460      */
 461     @Override
 462     protected Object clone() throws CloneNotSupportedException {
 463         throw new CloneNotSupportedException();
 464     }
 465 
 466     /**
 467      * Allocates a new {@code Thread} object. This constructor has the same
 468      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 469      * {@code (null, null, gname)}, where {@code gname} is a newly generated
 470      * name. Automatically generated names are of the form
 471      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
 472      */
 473     public Thread() {
 474         this(null, null, "Thread-" + nextThreadNum(), 0);


 875      * <p>
 876      * It is permitted to stop a thread that has not yet been started.
 877      * If the thread is eventually started, it immediately terminates.
 878      * <p>
 879      * An application should not normally try to catch
 880      * {@code ThreadDeath} unless it must do some extraordinary
 881      * cleanup operation (note that the throwing of
 882      * {@code ThreadDeath} causes {@code finally} clauses of
 883      * {@code try} statements to be executed before the thread
 884      * officially dies).  If a {@code catch} clause catches a
 885      * {@code ThreadDeath} object, it is important to rethrow the
 886      * object so that the thread actually dies.
 887      * <p>
 888      * The top-level error handler that reacts to otherwise uncaught
 889      * exceptions does not print out a message or otherwise notify the
 890      * application if the uncaught exception is an instance of
 891      * {@code ThreadDeath}.
 892      *
 893      * @throws     SecurityException  if the current thread cannot
 894      *             modify this thread.


 895      * @see        #interrupt()
 896      * @see        #checkAccess()
 897      * @see        #run()
 898      * @see        #start()
 899      * @see        ThreadDeath
 900      * @see        ThreadGroup#uncaughtException(Thread,Throwable)
 901      * @see        SecurityManager#checkAccess(Thread)
 902      * @see        SecurityManager#checkPermission
 903      * @deprecated This method is inherently unsafe.  Stopping a thread with
 904      *       Thread.stop causes it to unlock all of the monitors that it
 905      *       has locked (as a natural consequence of the unchecked
 906      *       {@code ThreadDeath} exception propagating up the stack).  If
 907      *       any of the objects previously protected by these monitors were in
 908      *       an inconsistent state, the damaged objects become visible to
 909      *       other threads, potentially resulting in arbitrary behavior.  Many
 910      *       uses of {@code stop} should be replaced by code that simply
 911      *       modifies some variable to indicate that the target thread should
 912      *       stop running.  The target thread should check this variable
 913      *       regularly, and return from its run method in an orderly fashion
 914      *       if the variable indicates that it is to stop running.  If the
 915      *       target thread waits for long periods (on a condition variable,
 916      *       for example), the {@code interrupt} method should be used to
 917      *       interrupt the wait.
 918      *       For more information, see
 919      *       <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
 920      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
 921      */
 922     @Deprecated(since="1.2")
 923     public final void stop() {
 924         SecurityManager security = System.getSecurityManager();
 925         if (security != null) {
 926             checkAccess();
 927             if (this != Thread.currentThread()) {
 928                 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
 929             }
 930         }




 931         // A zero status value corresponds to "NEW", it can't change to
 932         // not-NEW because we hold the lock.
 933         if (threadStatus != 0) {
 934             resume(); // Wake up thread if it was suspended; no-op otherwise
 935         }
 936 
 937         // The VM can handle all thread states
 938         stop0(new ThreadDeath());
 939     }
 940 
 941     /**
 942      * Interrupts this thread.
 943      *
 944      * <p> Unless the current thread is interrupting itself, which is
 945      * always permitted, the {@link #checkAccess() checkAccess} method
 946      * of this thread is invoked, which may cause a {@link
 947      * SecurityException} to be thrown.
 948      *
 949      * <p> If this thread is blocked in an invocation of the {@link
 950      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link


 997     }
 998 
 999     /**
1000      * Tests whether the current thread has been interrupted.  The
1001      * <i>interrupted status</i> of the thread is cleared by this method.  In
1002      * other words, if this method were to be called twice in succession, the
1003      * second call would return false (unless the current thread were
1004      * interrupted again, after the first call had cleared its interrupted
1005      * status and before the second call had examined it).
1006      *
1007      * <p>A thread interruption ignored because a thread was not alive
1008      * at the time of the interrupt will be reflected by this method
1009      * returning false.
1010      *
1011      * @return  {@code true} if the current thread has been interrupted;
1012      *          {@code false} otherwise.
1013      * @see #isInterrupted()
1014      * @revised 6.0
1015      */
1016     public static boolean interrupted() {
1017         return currentThread().isInterrupted(true);






1018     }
1019 
1020     /**
1021      * Tests whether this thread has been interrupted.  The <i>interrupted
1022      * status</i> of the thread is unaffected by this method.
1023      *
1024      * <p>A thread interruption ignored because a thread was not alive
1025      * at the time of the interrupt will be reflected by this method
1026      * returning false.
1027      *
1028      * @return  {@code true} if this thread has been interrupted;
1029      *          {@code false} otherwise.
1030      * @see     #interrupted()
1031      * @revised 6.0
1032      */
1033     public boolean isInterrupted() {
1034         return isInterrupted(false);
1035     }
1036 




1037     /**
1038      * Tests if some Thread has been interrupted.  The interrupted state
1039      * is reset or not based on the value of ClearInterrupted that is
1040      * passed.
1041      */
1042     @HotSpotIntrinsicCandidate
1043     private native boolean isInterrupted(boolean ClearInterrupted);
1044 
1045     /**
1046      * Tests if this thread is alive. A thread is alive if it has
1047      * been started and has not yet died.
1048      *
1049      * @return  {@code true} if this thread is alive;
1050      *          {@code false} otherwise.
1051      */
1052     public final native boolean isAlive();









1053 
1054     /**
1055      * Suspends this thread.
1056      * <p>
1057      * First, the {@code checkAccess} method of this thread is called
1058      * with no arguments. This may result in throwing a
1059      * {@code SecurityException }(in the current thread).
1060      * <p>
1061      * If the thread is alive, it is suspended and makes no further
1062      * progress unless and until it is resumed.
1063      *
1064      * @throws     SecurityException  if the current thread cannot modify
1065      *             this thread.


1066      * @see #checkAccess
1067      * @deprecated   This method has been deprecated, as it is
1068      *   inherently deadlock-prone.  If the target thread holds a lock on the
1069      *   monitor protecting a critical system resource when it is suspended, no
1070      *   thread can access this resource until the target thread is resumed. If
1071      *   the thread that would resume the target thread attempts to lock this
1072      *   monitor prior to calling {@code resume}, deadlock results.  Such
1073      *   deadlocks typically manifest themselves as "frozen" processes.
1074      *   For more information, see
1075      *   <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1076      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1077      */
1078     @Deprecated(since="1.2")
1079     public final void suspend() {
1080         checkAccess();






1081         suspend0();
1082     }
1083 
1084     /**
1085      * Resumes a suspended thread.
1086      * <p>
1087      * First, the {@code checkAccess} method of this thread is called
1088      * with no arguments. This may result in throwing a
1089      * {@code SecurityException} (in the current thread).
1090      * <p>
1091      * If the thread is alive but suspended, it is resumed and is
1092      * permitted to make progress in its execution.
1093      *
1094      * @throws     SecurityException  if the current thread cannot modify this
1095      *             thread.


1096      * @see        #checkAccess
1097      * @see        #suspend()
1098      * @deprecated This method exists solely for use with {@link #suspend},
1099      *     which has been deprecated because it is deadlock-prone.
1100      *     For more information, see
1101      *     <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1102      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1103      */
1104     @Deprecated(since="1.2")
1105     public final void resume() {
1106         checkAccess();






1107         resume0();
1108     }
1109 
1110     /**
1111      * Changes the priority of this thread.
1112      * <p>
1113      * First the {@code checkAccess} method of this thread is called
1114      * with no arguments. This may result in throwing a {@code SecurityException}.
1115      * <p>
1116      * Otherwise, the priority of this thread is set to the smaller of
1117      * the specified {@code newPriority} and the maximum permitted
1118      * priority of the thread's thread group.
1119      *
1120      * @param newPriority priority to set this thread to
1121      * @throws     IllegalArgumentException  If the priority is not in the
1122      *               range {@code MIN_PRIORITY} to
1123      *               {@code MAX_PRIORITY}.
1124      * @throws     SecurityException  if the current thread cannot modify
1125      *               this thread.
1126      * @see        #getPriority


1157     /**
1158      * Changes the name of this thread to be equal to the argument {@code name}.
1159      * <p>
1160      * First the {@code checkAccess} method of this thread is called
1161      * with no arguments. This may result in throwing a
1162      * {@code SecurityException}.
1163      *
1164      * @param      name   the new name for this thread.
1165      * @throws     SecurityException  if the current thread cannot modify this
1166      *             thread.
1167      * @see        #getName
1168      * @see        #checkAccess()
1169      */
1170     public final synchronized void setName(String name) {
1171         checkAccess();
1172         if (name == null) {
1173             throw new NullPointerException("name cannot be null");
1174         }
1175 
1176         this.name = name;
1177         if (threadStatus != 0) {
1178             setNativeName(name);
1179         }
1180     }
1181 
1182     /**
1183      * Returns this thread's name.
1184      *
1185      * @return  this thread's name.
1186      * @see     #setName(String)
1187      */
1188     public final String getName() {
1189         return name;
1190     }
1191 
1192     /**
1193      * Returns the thread group to which this thread belongs.
1194      * This method returns null if this thread has died
1195      * (been stopped).
1196      *
1197      * @return  this thread's thread group.


1270      * Waits at most {@code millis} milliseconds for this thread to
1271      * die. A timeout of {@code 0} means to wait forever.
1272      *
1273      * <p> This implementation uses a loop of {@code this.wait} calls
1274      * conditioned on {@code this.isAlive}. As a thread terminates the
1275      * {@code this.notifyAll} method is invoked. It is recommended that
1276      * applications not use {@code wait}, {@code notify}, or
1277      * {@code notifyAll} on {@code Thread} instances.
1278      *
1279      * @param  millis
1280      *         the time to wait in milliseconds
1281      *
1282      * @throws  IllegalArgumentException
1283      *          if the value of {@code millis} is negative
1284      *
1285      * @throws  InterruptedException
1286      *          if any thread has interrupted the current thread. The
1287      *          <i>interrupted status</i> of the current thread is
1288      *          cleared when this exception is thrown.
1289      */
1290     public final synchronized void join(final long millis)
1291     throws InterruptedException {
1292         if (millis > 0) {
1293             if (isAlive()) {
1294                 final long startTime = System.nanoTime();
1295                 long delay = millis;
1296                 do {
1297                     wait(delay);
1298                 } while (isAlive() && (delay = millis -
1299                         TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1300             }
1301         } else if (millis == 0) {
1302             while (isAlive()) {
1303                 wait(0);









1304             }
1305         } else {
1306             throw new IllegalArgumentException("timeout value is negative");
1307         }
1308     }
1309 
1310     /**
1311      * Waits at most {@code millis} milliseconds plus
1312      * {@code nanos} nanoseconds for this thread to die.
1313      * If both arguments are {@code 0}, it means to wait forever.
1314      *
1315      * <p> This implementation uses a loop of {@code this.wait} calls
1316      * conditioned on {@code this.isAlive}. As a thread terminates the
1317      * {@code this.notifyAll} method is invoked. It is recommended that
1318      * applications not use {@code wait}, {@code notify}, or
1319      * {@code notifyAll} on {@code Thread} instances.
1320      *
1321      * @param  millis
1322      *         the time to wait in milliseconds
1323      *
1324      * @param  nanos
1325      *         {@code 0-999999} additional nanoseconds to wait
1326      *
1327      * @throws  IllegalArgumentException
1328      *          if the value of {@code millis} is negative, or the value
1329      *          of {@code nanos} is not in the range {@code 0-999999}
1330      *
1331      * @throws  InterruptedException
1332      *          if any thread has interrupted the current thread. The
1333      *          <i>interrupted status</i> of the current thread is
1334      *          cleared when this exception is thrown.
1335      */
1336     public final synchronized void join(long millis, int nanos)
1337     throws InterruptedException {
1338 
1339         if (millis < 0) {
1340             throw new IllegalArgumentException("timeout value is negative");
1341         }
1342 
1343         if (nanos < 0 || nanos > 999999) {
1344             throw new IllegalArgumentException(
1345                                 "nanosecond timeout value out of range");
1346         }
1347 
1348         if (nanos > 0 && millis < Long.MAX_VALUE) {
1349             millis++;
1350         }
1351 
1352         join(millis);
1353     }
1354 
1355     /**
1356      * Waits for this thread to die.
1357      *
1358      * <p> An invocation of this method behaves in exactly the same


1365      * @throws  InterruptedException
1366      *          if any thread has interrupted the current thread. The
1367      *          <i>interrupted status</i> of the current thread is
1368      *          cleared when this exception is thrown.
1369      */
1370     public final void join() throws InterruptedException {
1371         join(0);
1372     }
1373 
1374     /**
1375      * Prints a stack trace of the current thread to the standard error stream.
1376      * This method is used only for debugging.
1377      */
1378     public static void dumpStack() {
1379         new Exception("Stack trace").printStackTrace();
1380     }
1381 
1382     /**
1383      * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1384      * or a user thread. The Java Virtual Machine exits when the only
1385      * threads running are all daemon threads.


1386      *
1387      * <p> This method must be invoked before the thread is started.
1388      *
1389      * @param  on
1390      *         if {@code true}, marks this thread as a daemon thread
1391      *
1392      * @throws  IllegalThreadStateException
1393      *          if this thread is {@linkplain #isAlive alive}
1394      *
1395      * @throws  SecurityException
1396      *          if {@link #checkAccess} determines that the current
1397      *          thread cannot modify this thread
1398      */
1399     public final void setDaemon(boolean on) {
1400         checkAccess();
1401         if (isAlive()) {
1402             throw new IllegalThreadStateException();
1403         }
1404         daemon = on;
1405     }


1470      *          if a security manager is present, and the caller's class loader
1471      *          is not {@code null} and is not the same as or an ancestor of the
1472      *          context class loader, and the caller does not have the
1473      *          {@link RuntimePermission}{@code ("getClassLoader")}
1474      *
1475      * @since 1.2
1476      */
1477     @CallerSensitive
1478     public ClassLoader getContextClassLoader() {
1479         if (contextClassLoader == null)
1480             return null;
1481         SecurityManager sm = System.getSecurityManager();
1482         if (sm != null) {
1483             ClassLoader.checkClassLoaderPermission(contextClassLoader,
1484                                                    Reflection.getCallerClass());
1485         }
1486         return contextClassLoader;
1487     }
1488 
1489     /**














1490      * Sets the context ClassLoader for this Thread. The context
1491      * ClassLoader can be set when a thread is created, and allows
1492      * the creator of the thread to provide the appropriate class loader,
1493      * through {@code getContextClassLoader}, to code running in the thread
1494      * when loading classes and resources.
1495      *
1496      * <p>If a security manager is present, its {@link
1497      * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1498      * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1499      * ("setContextClassLoader")} permission to see if setting the context
1500      * ClassLoader is permitted.
1501      *
1502      * @param  cl
1503      *         the context ClassLoader for this Thread, or null  indicating the
1504      *         system class loader (or, failing that, the bootstrap class loader)
1505      *
1506      * @throws  SecurityException
1507      *          if the current thread cannot set the context ClassLoader
1508      *
1509      * @since 1.2


1951         return defaultUncaughtExceptionHandler;
1952     }
1953 
1954     /**
1955      * Returns the handler invoked when this thread abruptly terminates
1956      * due to an uncaught exception. If this thread has not had an
1957      * uncaught exception handler explicitly set then this thread's
1958      * {@code ThreadGroup} object is returned, unless this thread
1959      * has terminated, in which case {@code null} is returned.
1960      * @since 1.5
1961      * @return the uncaught exception handler for this thread
1962      */
1963     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1964         return uncaughtExceptionHandler != null ?
1965             uncaughtExceptionHandler : group;
1966     }
1967 
1968     /**
1969      * Set the handler invoked when this thread abruptly terminates
1970      * due to an uncaught exception.

1971      * <p>A thread can take full control of how it responds to uncaught
1972      * exceptions by having its uncaught exception handler explicitly set.
1973      * If no such handler is set then the thread's {@code ThreadGroup}
1974      * object acts as its handler.
1975      * @param eh the object to use as this thread's uncaught exception
1976      * handler. If {@code null} then this thread has no explicit handler.
1977      * @throws  SecurityException  if the current thread is not allowed to
1978      *          modify this thread.
1979      * @see #setDefaultUncaughtExceptionHandler
1980      * @see ThreadGroup#uncaughtException
1981      * @since 1.5
1982      */
1983     public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1984         checkAccess();
1985         uncaughtExceptionHandler = eh;
1986     }
1987 
1988     /**
1989      * Dispatch an uncaught exception to the handler. This method is
1990      * intended to be called only by the JVM.

1991      */
1992     private void dispatchUncaughtException(Throwable e) {
1993         getUncaughtExceptionHandler().uncaughtException(this, e);
1994     }
1995 
1996     /**
1997      * Removes from the specified map any keys that have been enqueued
1998      * on the specified reference queue.
1999      */
2000     static void processQueue(ReferenceQueue<Class<?>> queue,
2001                              ConcurrentMap<? extends
2002                              WeakReference<Class<?>>, ?> map)
2003     {
2004         Reference<? extends Class<?>> ref;
2005         while((ref = queue.poll()) != null) {
2006             map.remove(ref);
2007         }
2008     }
2009 
2010     /**
2011      *  Weak key for Class objects.
2012      **/




  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;
  27 
  28 import java.lang.ref.Reference;
  29 import java.lang.ref.ReferenceQueue;
  30 import java.lang.ref.WeakReference;
  31 import java.security.AccessController;
  32 import java.security.AccessControlContext;
  33 import java.security.PrivilegedAction;
  34 import java.util.Map;
  35 import java.util.HashMap;
  36 import java.util.concurrent.ConcurrentHashMap;
  37 import java.util.concurrent.ConcurrentMap;
  38 import java.util.concurrent.TimeUnit;
  39 import java.util.concurrent.locks.LockSupport;
  40 
  41 import jdk.internal.misc.Strands;
  42 import jdk.internal.misc.TerminatingThreadLocal;
  43 import sun.nio.ch.Interruptible;
  44 import jdk.internal.reflect.CallerSensitive;
  45 import jdk.internal.reflect.Reflection;
  46 import sun.security.util.SecurityConstants;
  47 import jdk.internal.HotSpotIntrinsicCandidate;
  48 
  49 /**
  50  * A <i>thread</i> is a thread of execution in a program. The Java
  51  * Virtual Machine allows an application to have multiple threads of
  52  * execution running concurrently.
  53  * <p>
  54  * Every thread has a priority. Threads with higher priority are
  55  * executed in preference to threads with lower priority. Each thread
  56  * may or may not also be marked as a daemon. When code running in
  57  * some thread creates a new {@code Thread} object, the new
  58  * thread has its priority initially set equal to the priority of the
  59  * creating thread, and is a daemon thread if and only if the
  60  * creating thread is a daemon.
  61  * <p>


 182     ThreadLocal.ThreadLocalMap threadLocals = null;
 183 
 184     /*
 185      * InheritableThreadLocal values pertaining to this thread. This map is
 186      * maintained by the InheritableThreadLocal class.
 187      */
 188     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
 189 
 190     /*
 191      * The requested stack size for this thread, or 0 if the creator did
 192      * not specify a stack size.  It is up to the VM to do whatever it
 193      * likes with this number; some VMs will ignore it.
 194      */
 195     private final long stackSize;
 196 
 197     /*
 198      * Thread ID
 199      */
 200     private final long tid;
 201 
 202     /*
 203      * Current inner-most continuation
 204      */
 205     private Continuation cont;
 206 
 207     /* For generating thread ID */
 208     private static long threadSeqNumber;
 209 
 210     private static synchronized long nextThreadID() {
 211         return ++threadSeqNumber;
 212     }
 213 
 214     /*
 215      * Java thread status for tools, default indicates thread 'not yet started'
 216      */
 217     private volatile int threadStatus;
 218 
 219     /**
 220      * The argument supplied to the current call to
 221      * java.util.concurrent.locks.LockSupport.park.
 222      * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
 223      * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
 224      */
 225     volatile Object parkBlocker;
 226 
 227     /* The object in which this thread is blocked in an interruptible I/O
 228      * operation, if any.  The blocker's interrupt method should be invoked
 229      * after setting this thread's interrupt status.
 230      */
 231     private volatile Interruptible blocker;
 232     private final Object blockerLock = new Object();
 233 
 234     /* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
 235      * from java.nio code
 236      */
 237     static void blockedOn(Interruptible b) {
 238         Thread me = Thread.currentThread();
 239         synchronized (me.blockerLock) {
 240             me.blocker = b;
 241         }
 242     }
 243 
 244     Object blockerLock() {
 245         return blockerLock;
 246     }
 247 
 248     void runInterrupter() {
 249         assert Thread.holdsLock(blockerLock);
 250         Interruptible b = blocker;
 251         if (b != null) {
 252             b.interrupt(this);
 253         }
 254     }
 255 
 256     /**
 257      * The minimum priority that a thread can have.
 258      */
 259     public static final int MIN_PRIORITY = 1;
 260 
 261    /**
 262      * The default priority that is assigned to a thread.
 263      */
 264     public static final int NORM_PRIORITY = 5;
 265 
 266     /**
 267      * The maximum priority that a thread can have.
 268      */
 269     public static final int MAX_PRIORITY = 10;
 270 
 271     /**
 272      * Returns the Thread object for the current thread.
 273      *
 274      * <p> When executed in the context of a fiber, the returned Thread object
 275      * does not support all features of Thread. In particular, the Thread
 276      * is not an <i>active thread</i> in its thread group and so is not enumerated
 277      * or acted on by thread group operations. In addition it does not support
 278      * the stop, suspend or resume methods.
 279      *
 280      * @return  the current thread
 281      */
 282     public static Thread currentThread() {
 283         Thread t = currentThread0();
 284         Fiber<?> fiber = t.fiber;
 285         if (fiber != null) {
 286             return fiber.shadowThread();
 287         } else {
 288             return t;
 289         }
 290     }
 291 
 292     /**
 293      * Returns the current carrier thread.
 294      */
 295     static Thread currentCarrierThread() {
 296         return currentThread0();
 297     }
 298 
 299     @HotSpotIntrinsicCandidate
 300     private static native Thread currentThread0();
 301 
 302     private Fiber<?> fiber;
 303     private FiberScope scope;
 304 
 305     /**
 306      * Binds this thread to given Fiber. Once set, Thread.currentThread() will
 307      * return the Fiber rather than the Thread object for the carrier thread.
 308      */
 309     void setFiber(Fiber<?> fiber) {
 310         //assert this == currentThread0();
 311         this.fiber = fiber;
 312     }
 313 
 314     /**
 315      * Returns the Fiber that is currently bound to this thread.
 316      */
 317     Fiber<?> getFiber() {
 318         //assert this == currentThread0();
 319         return fiber;
 320     }
 321 
 322     FiberScope scope() {
 323         assert Thread.currentThread() == this;
 324         return scope;
 325     }
 326 
 327     void setScope(FiberScope scope) {
 328         assert Thread.currentThread() == this;
 329         this.scope = scope;
 330     }
 331 
 332     /**
 333      * A hint to the scheduler that the current thread is willing to yield
 334      * its current use of a processor. The scheduler is free to ignore this
 335      * hint.
 336      *
 337      * <p> Yield is a heuristic attempt to improve relative progression
 338      * between threads that would otherwise over-utilise a CPU. Its use
 339      * should be combined with detailed profiling and benchmarking to
 340      * ensure that it actually has the desired effect.
 341      *
 342      * <p> It is rarely appropriate to use this method. It may be useful
 343      * for debugging or testing purposes, where it may help to reproduce
 344      * bugs due to race conditions. It may also be useful when designing
 345      * concurrency control constructs such as the ones in the
 346      * {@link java.util.concurrent.locks} package.
 347      */
 348     public static void yield() {
 349         Fiber<?> fiber = currentCarrierThread().getFiber();
 350         if (fiber != null) {
 351             fiber.yield();
 352         } else {
 353             yield0();
 354         }
 355     }
 356     private static native void yield0();
 357 
 358     /**
 359      * Causes the currently executing thread to sleep (temporarily cease
 360      * execution) for the specified number of milliseconds, subject to
 361      * the precision and accuracy of system timers and schedulers. The thread
 362      * does not lose ownership of any monitors.
 363      *
 364      * @param  millis
 365      *         the length of time to sleep in milliseconds
 366      *
 367      * @throws  IllegalArgumentException
 368      *          if the value of {@code millis} is negative
 369      *
 370      * @throws  InterruptedException
 371      *          if any thread has interrupted the current thread. The
 372      *          <i>interrupted status</i> of the current thread is
 373      *          cleared when this exception is thrown.
 374      */
 375     public static void sleep(long millis) throws InterruptedException {
 376         if (millis < 0) {
 377             throw new IllegalArgumentException("timeout value is negative");
 378         }
 379         if (currentCarrierThread().getFiber() != null) {
 380             Fiber.sleepNanos(TimeUnit.MILLISECONDS.toNanos(millis));
 381         } else {
 382             sleep0(millis);
 383         }
 384     }
 385     private static native void sleep0(long millis) throws InterruptedException;
 386 
 387     /**
 388      * Causes the currently executing thread to sleep (temporarily cease
 389      * execution) for the specified number of milliseconds plus the specified
 390      * number of nanoseconds, subject to the precision and accuracy of system
 391      * timers and schedulers. The thread does not lose ownership of any
 392      * monitors.
 393      *
 394      * @param  millis
 395      *         the length of time to sleep in milliseconds
 396      *
 397      * @param  nanos
 398      *         {@code 0-999999} additional nanoseconds to sleep
 399      *
 400      * @throws  IllegalArgumentException
 401      *          if the value of {@code millis} is negative, or the value of
 402      *          {@code nanos} is not in the range {@code 0-999999}
 403      *
 404      * @throws  InterruptedException
 405      *          if any thread has interrupted the current thread. The
 406      *          <i>interrupted status</i> of the current thread is
 407      *          cleared when this exception is thrown.
 408      */
 409     public static void sleep(long millis, int nanos) throws InterruptedException {

 410         if (millis < 0) {
 411             throw new IllegalArgumentException("timeout value is negative");
 412         }
 413 
 414         if (nanos < 0 || nanos > 999999) {
 415             throw new IllegalArgumentException(
 416                                 "nanosecond timeout value out of range");
 417         }
 418 
 419         if (nanos > 0 && millis < Long.MAX_VALUE) {
 420             millis++;
 421         }
 422 
 423         sleep(millis);
 424     }
 425 
 426     /**
 427      * Indicates that the caller is momentarily unable to progress, until the
 428      * occurrence of one or more actions on the part of other activities. By
 429      * invoking this method within each iteration of a spin-wait loop construct,


 523         this.priority = parent.getPriority();
 524         if (security == null || isCCLOverridden(parent.getClass()))
 525             this.contextClassLoader = parent.getContextClassLoader();
 526         else
 527             this.contextClassLoader = parent.contextClassLoader;
 528         this.inheritedAccessControlContext =
 529                 acc != null ? acc : AccessController.getContext();
 530         this.target = target;
 531         setPriority(priority);
 532         if (inheritThreadLocals && parent.inheritableThreadLocals != null)
 533             this.inheritableThreadLocals =
 534                 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
 535         /* Stash the specified stack size in case the VM cares */
 536         this.stackSize = stackSize;
 537 
 538         /* Set thread ID */
 539         this.tid = nextThreadID();
 540     }
 541 
 542     /**
 543      * Initializes a Thread to be used as a shadow thread for Fibers.
 544      */
 545     Thread(ThreadGroup group,
 546            String name,
 547            ClassLoader contextClassLoader,
 548            ThreadLocal.ThreadLocalMap inheritedLocals,
 549            AccessControlContext inheritedAccessControlContext)
 550     {
 551         this.group = group;
 552         this.name = name;
 553         this.daemon = false;
 554         this.priority = NORM_PRIORITY;
 555         this.contextClassLoader = contextClassLoader;
 556         if (inheritedLocals != null) {
 557             this.inheritableThreadLocals = ThreadLocal.createInheritedMap(inheritedLocals);
 558         } else {
 559             this.inheritableThreadLocals = null;
 560         }
 561         this.inheritedAccessControlContext = inheritedAccessControlContext;
 562         this.stackSize = 0;
 563         this.tid = nextThreadID();
 564     }
 565 
 566     /**
 567      * Throws CloneNotSupportedException as a Thread can not be meaningfully
 568      * cloned. Construct a new Thread instead.
 569      *
 570      * @throws  CloneNotSupportedException
 571      *          always
 572      */
 573     @Override
 574     protected Object clone() throws CloneNotSupportedException {
 575         throw new CloneNotSupportedException();
 576     }
 577 
 578     /**
 579      * Allocates a new {@code Thread} object. This constructor has the same
 580      * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
 581      * {@code (null, null, gname)}, where {@code gname} is a newly generated
 582      * name. Automatically generated names are of the form
 583      * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
 584      */
 585     public Thread() {
 586         this(null, null, "Thread-" + nextThreadNum(), 0);


 987      * <p>
 988      * It is permitted to stop a thread that has not yet been started.
 989      * If the thread is eventually started, it immediately terminates.
 990      * <p>
 991      * An application should not normally try to catch
 992      * {@code ThreadDeath} unless it must do some extraordinary
 993      * cleanup operation (note that the throwing of
 994      * {@code ThreadDeath} causes {@code finally} clauses of
 995      * {@code try} statements to be executed before the thread
 996      * officially dies).  If a {@code catch} clause catches a
 997      * {@code ThreadDeath} object, it is important to rethrow the
 998      * object so that the thread actually dies.
 999      * <p>
1000      * The top-level error handler that reacts to otherwise uncaught
1001      * exceptions does not print out a message or otherwise notify the
1002      * application if the uncaught exception is an instance of
1003      * {@code ThreadDeath}.
1004      *
1005      * @throws     SecurityException  if the current thread cannot
1006      *             modify this thread.
1007      * @throws     UnsupportedOperationException if invoked on the Thread object
1008      *             for a Fiber
1009      * @see        #interrupt()
1010      * @see        #checkAccess()
1011      * @see        #run()
1012      * @see        #start()
1013      * @see        ThreadDeath
1014      * @see        ThreadGroup#uncaughtException(Thread,Throwable)
1015      * @see        SecurityManager#checkAccess(Thread)
1016      * @see        SecurityManager#checkPermission
1017      * @deprecated This method is inherently unsafe.  Stopping a thread with
1018      *       Thread.stop causes it to unlock all of the monitors that it
1019      *       has locked (as a natural consequence of the unchecked
1020      *       {@code ThreadDeath} exception propagating up the stack).  If
1021      *       any of the objects previously protected by these monitors were in
1022      *       an inconsistent state, the damaged objects become visible to
1023      *       other threads, potentially resulting in arbitrary behavior.  Many
1024      *       uses of {@code stop} should be replaced by code that simply
1025      *       modifies some variable to indicate that the target thread should
1026      *       stop running.  The target thread should check this variable
1027      *       regularly, and return from its run method in an orderly fashion
1028      *       if the variable indicates that it is to stop running.  If the
1029      *       target thread waits for long periods (on a condition variable,
1030      *       for example), the {@code interrupt} method should be used to
1031      *       interrupt the wait.
1032      *       For more information, see
1033      *       <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1034      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1035      */
1036     @Deprecated(since="1.2")
1037     public final void stop() {
1038         SecurityManager security = System.getSecurityManager();
1039         if (security != null) {
1040             checkAccess();
1041             if (this != Thread.currentThread()) {
1042                 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
1043             }
1044         }
1045 
1046         if (this instanceof ShadowThread)
1047             throw new UnsupportedOperationException();
1048 
1049         // A zero status value corresponds to "NEW", it can't change to
1050         // not-NEW because we hold the lock.
1051         if (threadStatus != 0) {
1052             resume(); // Wake up thread if it was suspended; no-op otherwise
1053         }
1054 
1055         // The VM can handle all thread states
1056         stop0(new ThreadDeath());
1057     }
1058 
1059     /**
1060      * Interrupts this thread.
1061      *
1062      * <p> Unless the current thread is interrupting itself, which is
1063      * always permitted, the {@link #checkAccess() checkAccess} method
1064      * of this thread is invoked, which may cause a {@link
1065      * SecurityException} to be thrown.
1066      *
1067      * <p> If this thread is blocked in an invocation of the {@link
1068      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link


1115     }
1116 
1117     /**
1118      * Tests whether the current thread has been interrupted.  The
1119      * <i>interrupted status</i> of the thread is cleared by this method.  In
1120      * other words, if this method were to be called twice in succession, the
1121      * second call would return false (unless the current thread were
1122      * interrupted again, after the first call had cleared its interrupted
1123      * status and before the second call had examined it).
1124      *
1125      * <p>A thread interruption ignored because a thread was not alive
1126      * at the time of the interrupt will be reflected by this method
1127      * returning false.
1128      *
1129      * @return  {@code true} if the current thread has been interrupted;
1130      *          {@code false} otherwise.
1131      * @see #isInterrupted()
1132      * @revised 6.0
1133      */
1134     public static boolean interrupted() {
1135         Thread thread = Thread.currentCarrierThread();
1136         Fiber<?> fiber = thread.getFiber();
1137         if (fiber != null) {
1138             return fiber.isInterrupted(true);
1139         } else {
1140             return thread.isInterrupted(true);
1141         }
1142     }
1143 
1144     /**
1145      * Tests whether this thread has been interrupted.  The <i>interrupted
1146      * status</i> of the thread is unaffected by this method.
1147      *
1148      * <p>A thread interruption ignored because a thread was not alive
1149      * at the time of the interrupt will be reflected by this method
1150      * returning false.
1151      *
1152      * @return  {@code true} if this thread has been interrupted;
1153      *          {@code false} otherwise.
1154      * @see     #interrupted()
1155      * @revised 6.0
1156      */
1157     public boolean isInterrupted() {
1158         return isInterrupted(false);
1159     }
1160 
1161     void clearInterrupt() {
1162         isInterrupted(true);
1163     }
1164 
1165     /**
1166      * Tests if some Thread has been interrupted.  The interrupted state
1167      * is reset or not based on the value of clearInterrupted that is
1168      * passed.
1169      */
1170     @HotSpotIntrinsicCandidate
1171     private native boolean isInterrupted(boolean clearInterrupted);
1172 
1173     /**
1174      * Tests if this thread is alive. A thread is alive if it has
1175      * been started and has not yet died.
1176      *
1177      * @return  {@code true} if this thread is alive;
1178      *          {@code false} otherwise.
1179      */
1180     public final boolean isAlive() {
1181         if (this instanceof ShadowThread) {
1182             State state = getState();
1183             assert state != State.NEW;
1184             return (state != State.TERMINATED);
1185         } else {
1186             return isAlive0();
1187         }
1188     }
1189     private native boolean isAlive0();
1190 
1191     /**
1192      * Suspends this thread.
1193      * <p>
1194      * First, the {@code checkAccess} method of this thread is called
1195      * with no arguments. This may result in throwing a
1196      * {@code SecurityException }(in the current thread).
1197      * <p>
1198      * If the thread is alive, it is suspended and makes no further
1199      * progress unless and until it is resumed.
1200      *
1201      * @throws     SecurityException  if the current thread cannot modify
1202      *             this thread.
1203      * @throws     UnsupportedOperationException if invoked on the Thread object
1204      *             for a Fiber
1205      * @see #checkAccess
1206      * @deprecated   This method has been deprecated, as it is
1207      *   inherently deadlock-prone.  If the target thread holds a lock on the
1208      *   monitor protecting a critical system resource when it is suspended, no
1209      *   thread can access this resource until the target thread is resumed. If
1210      *   the thread that would resume the target thread attempts to lock this
1211      *   monitor prior to calling {@code resume}, deadlock results.  Such
1212      *   deadlocks typically manifest themselves as "frozen" processes.
1213      *   For more information, see
1214      *   <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1215      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1216      */
1217     @Deprecated(since="1.2")
1218     public final void suspend() {
1219         checkAccess();
1220         if (this instanceof ShadowThread)
1221             throw new UnsupportedOperationException();
1222         suspend0();
1223     }
1224 
1225     void suspendThread() {
1226         suspend0();
1227     }
1228 
1229     /**
1230      * Resumes a suspended thread.
1231      * <p>
1232      * First, the {@code checkAccess} method of this thread is called
1233      * with no arguments. This may result in throwing a
1234      * {@code SecurityException} (in the current thread).
1235      * <p>
1236      * If the thread is alive but suspended, it is resumed and is
1237      * permitted to make progress in its execution.
1238      *
1239      * @throws     SecurityException  if the current thread cannot modify this
1240      *             thread.
1241      * @throws     UnsupportedOperationException if invoked on the Thread object
1242      *             for a Fiber
1243      * @see        #checkAccess
1244      * @see        #suspend()
1245      * @deprecated This method exists solely for use with {@link #suspend},
1246      *     which has been deprecated because it is deadlock-prone.
1247      *     For more information, see
1248      *     <a href="{@docRoot}/java.base/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
1249      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1250      */
1251     @Deprecated(since="1.2")
1252     public final void resume() {
1253         checkAccess();
1254         if (this instanceof ShadowThread)
1255             throw new UnsupportedOperationException();
1256         resume0();
1257     }
1258 
1259     void resumeThread() {
1260         resume0();
1261     }
1262 
1263     /**
1264      * Changes the priority of this thread.
1265      * <p>
1266      * First the {@code checkAccess} method of this thread is called
1267      * with no arguments. This may result in throwing a {@code SecurityException}.
1268      * <p>
1269      * Otherwise, the priority of this thread is set to the smaller of
1270      * the specified {@code newPriority} and the maximum permitted
1271      * priority of the thread's thread group.
1272      *
1273      * @param newPriority priority to set this thread to
1274      * @throws     IllegalArgumentException  If the priority is not in the
1275      *               range {@code MIN_PRIORITY} to
1276      *               {@code MAX_PRIORITY}.
1277      * @throws     SecurityException  if the current thread cannot modify
1278      *               this thread.
1279      * @see        #getPriority


1310     /**
1311      * Changes the name of this thread to be equal to the argument {@code name}.
1312      * <p>
1313      * First the {@code checkAccess} method of this thread is called
1314      * with no arguments. This may result in throwing a
1315      * {@code SecurityException}.
1316      *
1317      * @param      name   the new name for this thread.
1318      * @throws     SecurityException  if the current thread cannot modify this
1319      *             thread.
1320      * @see        #getName
1321      * @see        #checkAccess()
1322      */
1323     public final synchronized void setName(String name) {
1324         checkAccess();
1325         if (name == null) {
1326             throw new NullPointerException("name cannot be null");
1327         }
1328 
1329         this.name = name;
1330         if (!(this instanceof ShadowThread) && threadStatus != 0) {
1331             setNativeName(name);
1332         }
1333     }
1334 
1335     /**
1336      * Returns this thread's name.
1337      *
1338      * @return  this thread's name.
1339      * @see     #setName(String)
1340      */
1341     public final String getName() {
1342         return name;
1343     }
1344 
1345     /**
1346      * Returns the thread group to which this thread belongs.
1347      * This method returns null if this thread has died
1348      * (been stopped).
1349      *
1350      * @return  this thread's thread group.


1423      * Waits at most {@code millis} milliseconds for this thread to
1424      * die. A timeout of {@code 0} means to wait forever.
1425      *
1426      * <p> This implementation uses a loop of {@code this.wait} calls
1427      * conditioned on {@code this.isAlive}. As a thread terminates the
1428      * {@code this.notifyAll} method is invoked. It is recommended that
1429      * applications not use {@code wait}, {@code notify}, or
1430      * {@code notifyAll} on {@code Thread} instances.
1431      *
1432      * @param  millis
1433      *         the time to wait in milliseconds
1434      *
1435      * @throws  IllegalArgumentException
1436      *          if the value of {@code millis} is negative
1437      *
1438      * @throws  InterruptedException
1439      *          if any thread has interrupted the current thread. The
1440      *          <i>interrupted status</i> of the current thread is
1441      *          cleared when this exception is thrown.
1442      */
1443     public final void join(long millis) throws InterruptedException {
1444         if (this instanceof ShadowThread) {
1445             Fiber<?> fiber = ((ShadowThread) this).fiber();
1446             fiber.awaitInterruptibly(TimeUnit.MILLISECONDS.toNanos(millis));
1447             return;
1448         }
1449 
1450         synchronized (this) {
1451             if (millis > 0) {
1452                 if (isAlive()) {
1453                     final long startTime = System.nanoTime();
1454                     long delay = millis;
1455                     do {
1456                         wait(delay);
1457                     } while (isAlive() && (delay = millis -
1458                             TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
1459                 }
1460             } else if (millis == 0) {
1461                 while (isAlive()) {
1462                     wait(0);
1463                 }
1464             } else {
1465                 throw new IllegalArgumentException("timeout value is negative");
1466             }


1467         }
1468     }
1469 
1470     /**
1471      * Waits at most {@code millis} milliseconds plus
1472      * {@code nanos} nanoseconds for this thread to die.
1473      * If both arguments are {@code 0}, it means to wait forever.
1474      *
1475      * <p> This implementation uses a loop of {@code this.wait} calls
1476      * conditioned on {@code this.isAlive}. As a thread terminates the
1477      * {@code this.notifyAll} method is invoked. It is recommended that
1478      * applications not use {@code wait}, {@code notify}, or
1479      * {@code notifyAll} on {@code Thread} instances.
1480      *
1481      * @param  millis
1482      *         the time to wait in milliseconds
1483      *
1484      * @param  nanos
1485      *         {@code 0-999999} additional nanoseconds to wait
1486      *
1487      * @throws  IllegalArgumentException
1488      *          if the value of {@code millis} is negative, or the value
1489      *          of {@code nanos} is not in the range {@code 0-999999}
1490      *
1491      * @throws  InterruptedException
1492      *          if any thread has interrupted the current thread. The
1493      *          <i>interrupted status</i> of the current thread is
1494      *          cleared when this exception is thrown.
1495      */
1496     public final void join(long millis, int nanos) throws InterruptedException {


1497         if (millis < 0) {
1498             throw new IllegalArgumentException("timeout value is negative");
1499         }
1500 
1501         if (nanos < 0 || nanos > 999999) {
1502             throw new IllegalArgumentException(
1503                                 "nanosecond timeout value out of range");
1504         }
1505 
1506         if (nanos > 0 && millis < Long.MAX_VALUE) {
1507             millis++;
1508         }
1509 
1510         join(millis);
1511     }
1512 
1513     /**
1514      * Waits for this thread to die.
1515      *
1516      * <p> An invocation of this method behaves in exactly the same


1523      * @throws  InterruptedException
1524      *          if any thread has interrupted the current thread. The
1525      *          <i>interrupted status</i> of the current thread is
1526      *          cleared when this exception is thrown.
1527      */
1528     public final void join() throws InterruptedException {
1529         join(0);
1530     }
1531 
1532     /**
1533      * Prints a stack trace of the current thread to the standard error stream.
1534      * This method is used only for debugging.
1535      */
1536     public static void dumpStack() {
1537         new Exception("Stack trace").printStackTrace();
1538     }
1539 
1540     /**
1541      * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1542      * or a user thread. The Java Virtual Machine exits when the only
1543      * threads running are all daemon threads. The daemon status of {@code
1544      * Thread} objects associated with {@link Fiber}s is meaningless and does
1545      * not determine if the Java Virtual Machine exits or not.
1546      *
1547      * <p> This method must be invoked before the thread is started.
1548      *
1549      * @param  on
1550      *         if {@code true}, marks this thread as a daemon thread
1551      *
1552      * @throws  IllegalThreadStateException
1553      *          if this thread is {@linkplain #isAlive alive}
1554      *
1555      * @throws  SecurityException
1556      *          if {@link #checkAccess} determines that the current
1557      *          thread cannot modify this thread
1558      */
1559     public final void setDaemon(boolean on) {
1560         checkAccess();
1561         if (isAlive()) {
1562             throw new IllegalThreadStateException();
1563         }
1564         daemon = on;
1565     }


1630      *          if a security manager is present, and the caller's class loader
1631      *          is not {@code null} and is not the same as or an ancestor of the
1632      *          context class loader, and the caller does not have the
1633      *          {@link RuntimePermission}{@code ("getClassLoader")}
1634      *
1635      * @since 1.2
1636      */
1637     @CallerSensitive
1638     public ClassLoader getContextClassLoader() {
1639         if (contextClassLoader == null)
1640             return null;
1641         SecurityManager sm = System.getSecurityManager();
1642         if (sm != null) {
1643             ClassLoader.checkClassLoaderPermission(contextClassLoader,
1644                                                    Reflection.getCallerClass());
1645         }
1646         return contextClassLoader;
1647     }
1648 
1649     /**
1650      * TBD
1651      */
1652     Continuation getContinuation() {
1653         return cont;
1654     }
1655 
1656     /**
1657      * TBD
1658      */
1659     void setContinuation(Continuation cont) {
1660         this.cont = cont;
1661     }
1662 
1663     /**
1664      * Sets the context ClassLoader for this Thread. The context
1665      * ClassLoader can be set when a thread is created, and allows
1666      * the creator of the thread to provide the appropriate class loader,
1667      * through {@code getContextClassLoader}, to code running in the thread
1668      * when loading classes and resources.
1669      *
1670      * <p>If a security manager is present, its {@link
1671      * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1672      * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1673      * ("setContextClassLoader")} permission to see if setting the context
1674      * ClassLoader is permitted.
1675      *
1676      * @param  cl
1677      *         the context ClassLoader for this Thread, or null  indicating the
1678      *         system class loader (or, failing that, the bootstrap class loader)
1679      *
1680      * @throws  SecurityException
1681      *          if the current thread cannot set the context ClassLoader
1682      *
1683      * @since 1.2


2125         return defaultUncaughtExceptionHandler;
2126     }
2127 
2128     /**
2129      * Returns the handler invoked when this thread abruptly terminates
2130      * due to an uncaught exception. If this thread has not had an
2131      * uncaught exception handler explicitly set then this thread's
2132      * {@code ThreadGroup} object is returned, unless this thread
2133      * has terminated, in which case {@code null} is returned.
2134      * @since 1.5
2135      * @return the uncaught exception handler for this thread
2136      */
2137     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2138         return uncaughtExceptionHandler != null ?
2139             uncaughtExceptionHandler : group;
2140     }
2141 
2142     /**
2143      * Set the handler invoked when this thread abruptly terminates
2144      * due to an uncaught exception.
2145      *
2146      * <p>A thread can take full control of how it responds to uncaught
2147      * exceptions by having its uncaught exception handler explicitly set.
2148      * If no such handler is set then the thread's {@code ThreadGroup}
2149      * object acts as its handler.
2150      * @param eh the object to use as this thread's uncaught exception
2151      * handler. If {@code null} then this thread has no explicit handler.
2152      * @throws  SecurityException  if the current thread is not allowed to
2153      *          modify this thread.
2154      * @see #setDefaultUncaughtExceptionHandler
2155      * @see ThreadGroup#uncaughtException
2156      * @since 1.5
2157      */
2158     public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
2159         checkAccess();
2160         uncaughtExceptionHandler = eh;
2161     }
2162 
2163     /**
2164      * Dispatch an uncaught exception to the handler. This method is
2165      * called by the VM when a thread terminates with an exception. It is also
2166      * called when a fiber terminates with an exception.
2167      */
2168     void dispatchUncaughtException(Throwable e) {
2169         getUncaughtExceptionHandler().uncaughtException(this, e);
2170     }
2171 
2172     /**
2173      * Removes from the specified map any keys that have been enqueued
2174      * on the specified reference queue.
2175      */
2176     static void processQueue(ReferenceQueue<Class<?>> queue,
2177                              ConcurrentMap<? extends
2178                              WeakReference<Class<?>>, ?> map)
2179     {
2180         Reference<? extends Class<?>> ref;
2181         while((ref = queue.poll()) != null) {
2182             map.remove(ref);
2183         }
2184     }
2185 
2186     /**
2187      *  Weak key for Class objects.
2188      **/


< prev index next >