Print this page
Split |
Close |
Expand all |
Collapse all |
--- old/src/share/classes/java/lang/Thread.java
+++ new/src/share/classes/java/lang/Thread.java
1 1 /*
2 2 * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation. Oracle designates this
8 8 * particular file as subject to the "Classpath" exception as provided
9 9 * by Oracle in the LICENSE file that accompanied this code.
10 10 *
11 11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 14 * version 2 for more details (a copy is included in the LICENSE file that
15 15 * accompanied this code).
16 16 *
17 17 * You should have received a copy of the GNU General Public License version
18 18 * 2 along with this work; if not, write to the Free Software Foundation,
19 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 20 *
21 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 22 * or visit www.oracle.com if you need additional information or have any
23 23 * questions.
24 24 */
25 25
26 26 package java.lang;
27 27
28 28 import java.lang.ref.Reference;
29 29 import java.lang.ref.ReferenceQueue;
30 30 import java.lang.ref.WeakReference;
31 31 import java.security.AccessController;
32 32 import java.security.AccessControlContext;
33 33 import java.security.PrivilegedAction;
34 34 import java.util.Map;
35 35 import java.util.HashMap;
36 36 import java.util.concurrent.ConcurrentHashMap;
37 37 import java.util.concurrent.ConcurrentMap;
38 38 import java.util.concurrent.locks.LockSupport;
39 39 import sun.nio.ch.Interruptible;
40 40 import sun.security.util.SecurityConstants;
41 41
42 42
43 43 /**
44 44 * A <i>thread</i> is a thread of execution in a program. The Java
45 45 * Virtual Machine allows an application to have multiple threads of
46 46 * execution running concurrently.
47 47 * <p>
48 48 * Every thread has a priority. Threads with higher priority are
49 49 * executed in preference to threads with lower priority. Each thread
50 50 * may or may not also be marked as a daemon. When code running in
51 51 * some thread creates a new <code>Thread</code> object, the new
52 52 * thread has its priority initially set equal to the priority of the
53 53 * creating thread, and is a daemon thread if and only if the
54 54 * creating thread is a daemon.
55 55 * <p>
56 56 * When a Java Virtual Machine starts up, there is usually a single
57 57 * non-daemon thread (which typically calls the method named
58 58 * <code>main</code> of some designated class). The Java Virtual
59 59 * Machine continues to execute threads until either of the following
60 60 * occurs:
61 61 * <ul>
62 62 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
63 63 * called and the security manager has permitted the exit operation
64 64 * to take place.
65 65 * <li>All threads that are not daemon threads have died, either by
66 66 * returning from the call to the <code>run</code> method or by
67 67 * throwing an exception that propagates beyond the <code>run</code>
68 68 * method.
69 69 * </ul>
70 70 * <p>
71 71 * There are two ways to create a new thread of execution. One is to
72 72 * declare a class to be a subclass of <code>Thread</code>. This
73 73 * subclass should override the <code>run</code> method of class
74 74 * <code>Thread</code>. An instance of the subclass can then be
75 75 * allocated and started. For example, a thread that computes primes
76 76 * larger than a stated value could be written as follows:
77 77 * <p><hr><blockquote><pre>
78 78 * class PrimeThread extends Thread {
79 79 * long minPrime;
80 80 * PrimeThread(long minPrime) {
81 81 * this.minPrime = minPrime;
82 82 * }
83 83 *
84 84 * public void run() {
85 85 * // compute primes larger than minPrime
86 86 * . . .
87 87 * }
88 88 * }
89 89 * </pre></blockquote><hr>
90 90 * <p>
91 91 * The following code would then create a thread and start it running:
92 92 * <p><blockquote><pre>
93 93 * PrimeThread p = new PrimeThread(143);
94 94 * p.start();
95 95 * </pre></blockquote>
96 96 * <p>
97 97 * The other way to create a thread is to declare a class that
98 98 * implements the <code>Runnable</code> interface. That class then
99 99 * implements the <code>run</code> method. An instance of the class can
100 100 * then be allocated, passed as an argument when creating
101 101 * <code>Thread</code>, and started. The same example in this other
102 102 * style looks like the following:
103 103 * <p><hr><blockquote><pre>
104 104 * class PrimeRun implements Runnable {
105 105 * long minPrime;
106 106 * PrimeRun(long minPrime) {
107 107 * this.minPrime = minPrime;
108 108 * }
109 109 *
110 110 * public void run() {
111 111 * // compute primes larger than minPrime
112 112 * . . .
113 113 * }
114 114 * }
115 115 * </pre></blockquote><hr>
116 116 * <p>
117 117 * The following code would then create a thread and start it running:
118 118 * <p><blockquote><pre>
119 119 * PrimeRun p = new PrimeRun(143);
120 120 * new Thread(p).start();
121 121 * </pre></blockquote>
122 122 * <p>
123 123 * Every thread has a name for identification purposes. More than
124 124 * one thread may have the same name. If a name is not specified when
125 125 * a thread is created, a new name is generated for it.
126 126 * <p>
127 127 * Unless otherwise noted, passing a {@code null} argument to a constructor
128 128 * or method in this class will cause a {@link NullPointerException} to be
129 129 * thrown.
130 130 *
131 131 * @author unascribed
132 132 * @see Runnable
133 133 * @see Runtime#exit(int)
134 134 * @see #run()
135 135 * @see #stop()
136 136 * @since JDK1.0
137 137 */
138 138 public
139 139 class Thread implements Runnable {
140 140 /* Make sure registerNatives is the first thing <clinit> does. */
141 141 private static native void registerNatives();
142 142 static {
143 143 registerNatives();
144 144 }
145 145
146 146 private char name[];
147 147 private int priority;
148 148 private Thread threadQ;
149 149 private long eetop;
150 150
151 151 /* Whether or not to single_step this thread. */
152 152 private boolean single_step;
153 153
154 154 /* Whether or not the thread is a daemon thread. */
155 155 private boolean daemon = false;
156 156
157 157 /* JVM state */
158 158 private boolean stillborn = false;
159 159
160 160 /* What will be run. */
161 161 private Runnable target;
162 162
163 163 /* The group of this thread */
164 164 private ThreadGroup group;
165 165
166 166 /* The context ClassLoader for this thread */
167 167 private ClassLoader contextClassLoader;
168 168
169 169 /* The inherited AccessControlContext of this thread */
170 170 private AccessControlContext inheritedAccessControlContext;
171 171
172 172 /* For autonumbering anonymous threads. */
173 173 private static int threadInitNumber;
174 174 private static synchronized int nextThreadNum() {
175 175 return threadInitNumber++;
176 176 }
177 177
178 178 /* ThreadLocal values pertaining to this thread. This map is maintained
179 179 * by the ThreadLocal class. */
180 180 ThreadLocal.ThreadLocalMap threadLocals = null;
181 181
182 182 /*
183 183 * InheritableThreadLocal values pertaining to this thread. This map is
184 184 * maintained by the InheritableThreadLocal class.
185 185 */
186 186 ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
187 187
188 188 /*
189 189 * The requested stack size for this thread, or 0 if the creator did
190 190 * not specify a stack size. It is up to the VM to do whatever it
191 191 * likes with this number; some VMs will ignore it.
192 192 */
193 193 private long stackSize;
194 194
195 195 /*
196 196 * JVM-private state that persists after native thread termination.
197 197 */
198 198 private long nativeParkEventPointer;
199 199
200 200 /*
201 201 * Thread ID
202 202 */
203 203 private long tid;
204 204
205 205 /* For generating thread ID */
206 206 private static long threadSeqNumber;
207 207
208 208 /* Java thread status for tools,
209 209 * initialized to indicate thread 'not yet started'
210 210 */
211 211
212 212 private int threadStatus = 0;
213 213
214 214
215 215 private static synchronized long nextThreadID() {
216 216 return ++threadSeqNumber;
217 217 }
218 218
219 219 /**
220 220 * The argument supplied to the current call to
221 221 * java.util.concurrent.locks.LockSupport.park.
↓ open down ↓ |
221 lines elided |
↑ open up ↑ |
222 222 * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
223 223 * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
224 224 */
225 225 volatile Object parkBlocker;
226 226
227 227 /* The object in which this thread is blocked in an interruptible I/O
228 228 * operation, if any. The blocker's interrupt method should be invoked
229 229 * after setting this thread's interrupt status.
230 230 */
231 231 private volatile Interruptible blocker;
232 - private Object blockerLock = new Object();
232 + private final Object blockerLock = new Object();
233 233
234 234 /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
235 235 */
236 236 void blockedOn(Interruptible b) {
237 237 synchronized (blockerLock) {
238 238 blocker = b;
239 239 }
240 240 }
241 241
242 242 /**
243 243 * The minimum priority that a thread can have.
244 244 */
245 245 public final static int MIN_PRIORITY = 1;
246 246
247 247 /**
248 248 * The default priority that is assigned to a thread.
249 249 */
250 250 public final static int NORM_PRIORITY = 5;
251 251
252 252 /**
253 253 * The maximum priority that a thread can have.
254 254 */
255 255 public final static int MAX_PRIORITY = 10;
256 256
257 257 /* If stop was called before start */
258 258 private boolean stopBeforeStart;
259 259
260 260 /* Remembered Throwable from stop before start */
261 261 private Throwable throwableFromStop;
262 262
263 263 /**
264 264 * Returns a reference to the currently executing thread object.
265 265 *
266 266 * @return the currently executing thread.
267 267 */
268 268 public static native Thread currentThread();
269 269
270 270 /**
271 271 * A hint to the scheduler that the current thread is willing to yield
272 272 * its current use of a processor. The scheduler is free to ignore this
273 273 * hint.
274 274 *
275 275 * <p> Yield is a heuristic attempt to improve relative progression
276 276 * between threads that would otherwise over-utilise a CPU. Its use
277 277 * should be combined with detailed profiling and benchmarking to
278 278 * ensure that it actually has the desired effect.
279 279 *
280 280 * <p> It is rarely appropriate to use this method. It may be useful
281 281 * for debugging or testing purposes, where it may help to reproduce
282 282 * bugs due to race conditions. It may also be useful when designing
283 283 * concurrency control constructs such as the ones in the
284 284 * {@link java.util.concurrent.locks} package.
285 285 */
286 286 public static native void yield();
287 287
288 288 /**
289 289 * Causes the currently executing thread to sleep (temporarily cease
290 290 * execution) for the specified number of milliseconds, subject to
291 291 * the precision and accuracy of system timers and schedulers. The thread
292 292 * does not lose ownership of any monitors.
293 293 *
294 294 * @param millis
295 295 * the length of time to sleep in milliseconds
296 296 *
297 297 * @throws IllegalArgumentException
298 298 * if the value of {@code millis} is negative
299 299 *
300 300 * @throws InterruptedException
301 301 * if any thread has interrupted the current thread. The
302 302 * <i>interrupted status</i> of the current thread is
303 303 * cleared when this exception is thrown.
304 304 */
305 305 public static native void sleep(long millis) throws InterruptedException;
306 306
307 307 /**
308 308 * Causes the currently executing thread to sleep (temporarily cease
309 309 * execution) for the specified number of milliseconds plus the specified
310 310 * number of nanoseconds, subject to the precision and accuracy of system
311 311 * timers and schedulers. The thread does not lose ownership of any
312 312 * monitors.
313 313 *
314 314 * @param millis
315 315 * the length of time to sleep in milliseconds
316 316 *
317 317 * @param nanos
318 318 * {@code 0-999999} additional nanoseconds to sleep
319 319 *
320 320 * @throws IllegalArgumentException
321 321 * if the value of {@code millis} is negative, or the value of
322 322 * {@code nanos} is not in the range {@code 0-999999}
323 323 *
324 324 * @throws InterruptedException
325 325 * if any thread has interrupted the current thread. The
326 326 * <i>interrupted status</i> of the current thread is
327 327 * cleared when this exception is thrown.
328 328 */
329 329 public static void sleep(long millis, int nanos)
330 330 throws InterruptedException {
331 331 if (millis < 0) {
332 332 throw new IllegalArgumentException("timeout value is negative");
333 333 }
334 334
335 335 if (nanos < 0 || nanos > 999999) {
336 336 throw new IllegalArgumentException(
337 337 "nanosecond timeout value out of range");
338 338 }
339 339
340 340 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
341 341 millis++;
342 342 }
343 343
344 344 sleep(millis);
345 345 }
346 346
347 347 /**
348 348 * Initializes a Thread.
349 349 *
350 350 * @param g the Thread group
351 351 * @param target the object whose run() method gets called
352 352 * @param name the name of the new Thread
353 353 * @param stackSize the desired stack size for the new thread, or
354 354 * zero to indicate that this parameter is to be ignored.
355 355 */
356 356 private void init(ThreadGroup g, Runnable target, String name,
357 357 long stackSize) {
358 358 if (name == null) {
359 359 throw new NullPointerException("name cannot be null");
360 360 }
361 361
362 362 Thread parent = currentThread();
363 363 SecurityManager security = System.getSecurityManager();
364 364 if (g == null) {
365 365 /* Determine if it's an applet or not */
366 366
367 367 /* If there is a security manager, ask the security manager
368 368 what to do. */
369 369 if (security != null) {
370 370 g = security.getThreadGroup();
371 371 }
372 372
373 373 /* If the security doesn't have a strong opinion of the matter
374 374 use the parent thread group. */
375 375 if (g == null) {
376 376 g = parent.getThreadGroup();
377 377 }
378 378 }
379 379
380 380 /* checkAccess regardless of whether or not threadgroup is
381 381 explicitly passed in. */
382 382 g.checkAccess();
383 383
384 384 /*
385 385 * Do we have the required permissions?
386 386 */
387 387 if (security != null) {
388 388 if (isCCLOverridden(getClass())) {
389 389 security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
390 390 }
391 391 }
392 392
393 393 g.addUnstarted();
394 394
395 395 this.group = g;
396 396 this.daemon = parent.isDaemon();
397 397 this.priority = parent.getPriority();
398 398 this.name = name.toCharArray();
399 399 if (security == null || isCCLOverridden(parent.getClass()))
400 400 this.contextClassLoader = parent.getContextClassLoader();
401 401 else
402 402 this.contextClassLoader = parent.contextClassLoader;
403 403 this.inheritedAccessControlContext = AccessController.getContext();
404 404 this.target = target;
405 405 setPriority(priority);
406 406 if (parent.inheritableThreadLocals != null)
407 407 this.inheritableThreadLocals =
408 408 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
409 409 /* Stash the specified stack size in case the VM cares */
410 410 this.stackSize = stackSize;
411 411
412 412 /* Set thread ID */
413 413 tid = nextThreadID();
414 414 }
415 415
416 416 /**
417 417 * Throws CloneNotSupportedException as a Thread can not be meaningfully
418 418 * cloned. Construct a new Thread instead.
419 419 *
420 420 * @throws CloneNotSupportedException
421 421 * always
422 422 */
423 423 @Override
424 424 protected Object clone() throws CloneNotSupportedException {
425 425 throw new CloneNotSupportedException();
426 426 }
427 427
428 428 /**
429 429 * Allocates a new {@code Thread} object. This constructor has the same
430 430 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
431 431 * {@code (null, null, gname)}, where {@code gname} is a newly generated
432 432 * name. Automatically generated names are of the form
433 433 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
434 434 */
435 435 public Thread() {
436 436 init(null, null, "Thread-" + nextThreadNum(), 0);
437 437 }
438 438
439 439 /**
440 440 * Allocates a new {@code Thread} object. This constructor has the same
441 441 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
442 442 * {@code (null, target, gname)}, where {@code gname} is a newly generated
443 443 * name. Automatically generated names are of the form
444 444 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
445 445 *
446 446 * @param target
447 447 * the object whose {@code run} method is invoked when this thread
448 448 * is started. If {@code null}, this classes {@code run} method does
449 449 * nothing.
450 450 */
451 451 public Thread(Runnable target) {
452 452 init(null, target, "Thread-" + nextThreadNum(), 0);
453 453 }
454 454
455 455 /**
456 456 * Allocates a new {@code Thread} object. This constructor has the same
457 457 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
458 458 * {@code (group, target, gname)} ,where {@code gname} is a newly generated
459 459 * name. Automatically generated names are of the form
460 460 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
461 461 *
462 462 * @param group
463 463 * the thread group. If {@code null} and there is a security
464 464 * manager, the group is determined by {@linkplain
465 465 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
466 466 * If there is not a security manager or {@code
467 467 * SecurityManager.getThreadGroup()} returns {@code null}, the group
468 468 * is set to the current thread's thread group.
469 469 *
470 470 * @param target
471 471 * the object whose {@code run} method is invoked when this thread
472 472 * is started. If {@code null}, this thread's run method is invoked.
473 473 *
474 474 * @throws SecurityException
475 475 * if the current thread cannot create a thread in the specified
476 476 * thread group
477 477 */
478 478 public Thread(ThreadGroup group, Runnable target) {
479 479 init(group, target, "Thread-" + nextThreadNum(), 0);
480 480 }
481 481
482 482 /**
483 483 * Allocates a new {@code Thread} object. This constructor has the same
484 484 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
485 485 * {@code (null, null, name)}.
486 486 *
487 487 * @param name
488 488 * the name of the new thread
489 489 */
490 490 public Thread(String name) {
491 491 init(null, null, name, 0);
492 492 }
493 493
494 494 /**
495 495 * Allocates a new {@code Thread} object. This constructor has the same
496 496 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
497 497 * {@code (group, null, name)}.
498 498 *
499 499 * @param group
500 500 * the thread group. If {@code null} and there is a security
501 501 * manager, the group is determined by {@linkplain
502 502 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
503 503 * If there is not a security manager or {@code
504 504 * SecurityManager.getThreadGroup()} returns {@code null}, the group
505 505 * is set to the current thread's thread group.
506 506 *
507 507 * @param name
508 508 * the name of the new thread
509 509 *
510 510 * @throws SecurityException
511 511 * if the current thread cannot create a thread in the specified
512 512 * thread group
513 513 */
514 514 public Thread(ThreadGroup group, String name) {
515 515 init(group, null, name, 0);
516 516 }
517 517
518 518 /**
519 519 * Allocates a new {@code Thread} object. This constructor has the same
520 520 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
521 521 * {@code (null, target, name)}.
522 522 *
523 523 * @param target
524 524 * the object whose {@code run} method is invoked when this thread
525 525 * is started. If {@code null}, this thread's run method is invoked.
526 526 *
527 527 * @param name
528 528 * the name of the new thread
529 529 */
530 530 public Thread(Runnable target, String name) {
531 531 init(null, target, name, 0);
532 532 }
533 533
534 534 /**
535 535 * Allocates a new {@code Thread} object so that it has {@code target}
536 536 * as its run object, has the specified {@code name} as its name,
537 537 * and belongs to the thread group referred to by {@code group}.
538 538 *
539 539 * <p>If there is a security manager, its
540 540 * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
541 541 * method is invoked with the ThreadGroup as its argument.
542 542 *
543 543 * <p>In addition, its {@code checkPermission} method is invoked with
544 544 * the {@code RuntimePermission("enableContextClassLoaderOverride")}
545 545 * permission when invoked directly or indirectly by the constructor
546 546 * of a subclass which overrides the {@code getContextClassLoader}
547 547 * or {@code setContextClassLoader} methods.
548 548 *
549 549 * <p>The priority of the newly created thread is set equal to the
550 550 * priority of the thread creating it, that is, the currently running
551 551 * thread. The method {@linkplain #setPriority setPriority} may be
552 552 * used to change the priority to a new value.
553 553 *
554 554 * <p>The newly created thread is initially marked as being a daemon
555 555 * thread if and only if the thread creating it is currently marked
556 556 * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
557 557 * may be used to change whether or not a thread is a daemon.
558 558 *
559 559 * @param group
560 560 * the thread group. If {@code null} and there is a security
561 561 * manager, the group is determined by {@linkplain
562 562 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
563 563 * If there is not a security manager or {@code
564 564 * SecurityManager.getThreadGroup()} returns {@code null}, the group
565 565 * is set to the current thread's thread group.
566 566 *
567 567 * @param target
568 568 * the object whose {@code run} method is invoked when this thread
569 569 * is started. If {@code null}, this thread's run method is invoked.
570 570 *
571 571 * @param name
572 572 * the name of the new thread
573 573 *
574 574 * @throws SecurityException
575 575 * if the current thread cannot create a thread in the specified
576 576 * thread group or cannot override the context class loader methods.
577 577 */
578 578 public Thread(ThreadGroup group, Runnable target, String name) {
579 579 init(group, target, name, 0);
580 580 }
581 581
582 582 /**
583 583 * Allocates a new {@code Thread} object so that it has {@code target}
584 584 * as its run object, has the specified {@code name} as its name,
585 585 * and belongs to the thread group referred to by {@code group}, and has
586 586 * the specified <i>stack size</i>.
587 587 *
588 588 * <p>This constructor is identical to {@link
589 589 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
590 590 * that it allows the thread stack size to be specified. The stack size
591 591 * is the approximate number of bytes of address space that the virtual
592 592 * machine is to allocate for this thread's stack. <b>The effect of the
593 593 * {@code stackSize} parameter, if any, is highly platform dependent.</b>
594 594 *
595 595 * <p>On some platforms, specifying a higher value for the
596 596 * {@code stackSize} parameter may allow a thread to achieve greater
597 597 * recursion depth before throwing a {@link StackOverflowError}.
598 598 * Similarly, specifying a lower value may allow a greater number of
599 599 * threads to exist concurrently without throwing an {@link
600 600 * OutOfMemoryError} (or other internal error). The details of
601 601 * the relationship between the value of the <tt>stackSize</tt> parameter
602 602 * and the maximum recursion depth and concurrency level are
603 603 * platform-dependent. <b>On some platforms, the value of the
604 604 * {@code stackSize} parameter may have no effect whatsoever.</b>
605 605 *
606 606 * <p>The virtual machine is free to treat the {@code stackSize}
607 607 * parameter as a suggestion. If the specified value is unreasonably low
608 608 * for the platform, the virtual machine may instead use some
609 609 * platform-specific minimum value; if the specified value is unreasonably
610 610 * high, the virtual machine may instead use some platform-specific
611 611 * maximum. Likewise, the virtual machine is free to round the specified
612 612 * value up or down as it sees fit (or to ignore it completely).
613 613 *
614 614 * <p>Specifying a value of zero for the {@code stackSize} parameter will
615 615 * cause this constructor to behave exactly like the
616 616 * {@code Thread(ThreadGroup, Runnable, String)} constructor.
617 617 *
618 618 * <p><i>Due to the platform-dependent nature of the behavior of this
619 619 * constructor, extreme care should be exercised in its use.
620 620 * The thread stack size necessary to perform a given computation will
621 621 * likely vary from one JRE implementation to another. In light of this
622 622 * variation, careful tuning of the stack size parameter may be required,
623 623 * and the tuning may need to be repeated for each JRE implementation on
624 624 * which an application is to run.</i>
625 625 *
626 626 * <p>Implementation note: Java platform implementers are encouraged to
627 627 * document their implementation's behavior with respect to the
628 628 * {@code stackSize} parameter.
629 629 *
630 630 *
631 631 * @param group
632 632 * the thread group. If {@code null} and there is a security
633 633 * manager, the group is determined by {@linkplain
634 634 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
635 635 * If there is not a security manager or {@code
636 636 * SecurityManager.getThreadGroup()} returns {@code null}, the group
637 637 * is set to the current thread's thread group.
638 638 *
639 639 * @param target
640 640 * the object whose {@code run} method is invoked when this thread
641 641 * is started. If {@code null}, this thread's run method is invoked.
642 642 *
643 643 * @param name
644 644 * the name of the new thread
645 645 *
646 646 * @param stackSize
647 647 * the desired stack size for the new thread, or zero to indicate
648 648 * that this parameter is to be ignored.
649 649 *
650 650 * @throws SecurityException
651 651 * if the current thread cannot create a thread in the specified
652 652 * thread group
653 653 *
654 654 * @since 1.4
655 655 */
656 656 public Thread(ThreadGroup group, Runnable target, String name,
657 657 long stackSize) {
658 658 init(group, target, name, stackSize);
659 659 }
660 660
661 661 /**
662 662 * Causes this thread to begin execution; the Java Virtual Machine
663 663 * calls the <code>run</code> method of this thread.
664 664 * <p>
665 665 * The result is that two threads are running concurrently: the
666 666 * current thread (which returns from the call to the
667 667 * <code>start</code> method) and the other thread (which executes its
668 668 * <code>run</code> method).
669 669 * <p>
670 670 * It is never legal to start a thread more than once.
671 671 * In particular, a thread may not be restarted once it has completed
672 672 * execution.
673 673 *
674 674 * @exception IllegalThreadStateException if the thread was already
675 675 * started.
676 676 * @see #run()
677 677 * @see #stop()
678 678 */
679 679 public synchronized void start() {
680 680 /**
↓ open down ↓ |
438 lines elided |
↑ open up ↑ |
681 681 * This method is not invoked for the main method thread or "system"
682 682 * group threads created/set up by the VM. Any new functionality added
683 683 * to this method in the future may have to also be added to the VM.
684 684 *
685 685 * A zero status value corresponds to state "NEW".
686 686 */
687 687 if (threadStatus != 0)
688 688 throw new IllegalThreadStateException();
689 689
690 690 /* Notify the group that this thread is about to be started
691 - * so that it can be added to the group's list of threads. */
691 + * so that it can be added to the group's list of threads
692 + * and the group's unstarted count can be decremented. */
692 693 group.threadStarting(this);
693 694
694 - boolean failed = true;
695 + boolean started = false;
695 696 try {
696 697 start0();
697 - failed = false;
698 + started = true;
698 699 } finally {
699 700 try {
700 - group.threadStarted(this, failed);
701 + if (!started) {
702 + group.threadStartFailed(this);
703 + }
701 704 } catch (Throwable ignore) {
702 705 /* do nothing. If start0 threw a Throwable then
703 706 it will be passed up the call stack */
704 707 }
705 708 }
706 709
707 710 if (stopBeforeStart) {
708 711 stop0(throwableFromStop);
709 712 }
710 713 }
711 714
712 715 private native void start0();
713 716
714 717 /**
715 718 * If this thread was constructed using a separate
716 719 * <code>Runnable</code> run object, then that
717 720 * <code>Runnable</code> object's <code>run</code> method is called;
718 721 * otherwise, this method does nothing and returns.
719 722 * <p>
720 723 * Subclasses of <code>Thread</code> should override this method.
721 724 *
722 725 * @see #start()
723 726 * @see #stop()
724 727 * @see #Thread(ThreadGroup, Runnable, String)
725 728 */
726 729 @Override
727 730 public void run() {
728 731 if (target != null) {
729 732 target.run();
730 733 }
731 734 }
732 735
733 736 /**
734 737 * This method is called by the system to give a Thread
735 738 * a chance to clean up before it actually exits.
736 739 */
737 740 private void exit() {
738 741 if (group != null) {
739 742 group.threadTerminated(this);
740 743 group = null;
741 744 }
742 745 /* Aggressively null out all reference fields: see bug 4006245 */
743 746 target = null;
744 747 /* Speed the release of some of these resources */
745 748 threadLocals = null;
746 749 inheritableThreadLocals = null;
747 750 inheritedAccessControlContext = null;
748 751 blocker = null;
749 752 uncaughtExceptionHandler = null;
750 753 }
751 754
752 755 /**
753 756 * Forces the thread to stop executing.
754 757 * <p>
755 758 * If there is a security manager installed, its <code>checkAccess</code>
756 759 * method is called with <code>this</code>
757 760 * as its argument. This may result in a
758 761 * <code>SecurityException</code> being raised (in the current thread).
759 762 * <p>
760 763 * If this thread is different from the current thread (that is, the current
761 764 * thread is trying to stop a thread other than itself), the
762 765 * security manager's <code>checkPermission</code> method (with a
763 766 * <code>RuntimePermission("stopThread")</code> argument) is called in
764 767 * addition.
765 768 * Again, this may result in throwing a
766 769 * <code>SecurityException</code> (in the current thread).
767 770 * <p>
768 771 * The thread represented by this thread is forced to stop whatever
769 772 * it is doing abnormally and to throw a newly created
770 773 * <code>ThreadDeath</code> object as an exception.
771 774 * <p>
772 775 * It is permitted to stop a thread that has not yet been started.
773 776 * If the thread is eventually started, it immediately terminates.
774 777 * <p>
775 778 * An application should not normally try to catch
776 779 * <code>ThreadDeath</code> unless it must do some extraordinary
777 780 * cleanup operation (note that the throwing of
778 781 * <code>ThreadDeath</code> causes <code>finally</code> clauses of
779 782 * <code>try</code> statements to be executed before the thread
780 783 * officially dies). If a <code>catch</code> clause catches a
781 784 * <code>ThreadDeath</code> object, it is important to rethrow the
782 785 * object so that the thread actually dies.
783 786 * <p>
784 787 * The top-level error handler that reacts to otherwise uncaught
785 788 * exceptions does not print out a message or otherwise notify the
786 789 * application if the uncaught exception is an instance of
787 790 * <code>ThreadDeath</code>.
788 791 *
789 792 * @exception SecurityException if the current thread cannot
790 793 * modify this thread.
791 794 * @see #interrupt()
792 795 * @see #checkAccess()
793 796 * @see #run()
794 797 * @see #start()
795 798 * @see ThreadDeath
796 799 * @see ThreadGroup#uncaughtException(Thread,Throwable)
797 800 * @see SecurityManager#checkAccess(Thread)
798 801 * @see SecurityManager#checkPermission
799 802 * @deprecated This method is inherently unsafe. Stopping a thread with
800 803 * Thread.stop causes it to unlock all of the monitors that it
801 804 * has locked (as a natural consequence of the unchecked
802 805 * <code>ThreadDeath</code> exception propagating up the stack). If
803 806 * any of the objects previously protected by these monitors were in
804 807 * an inconsistent state, the damaged objects become visible to
805 808 * other threads, potentially resulting in arbitrary behavior. Many
806 809 * uses of <code>stop</code> should be replaced by code that simply
807 810 * modifies some variable to indicate that the target thread should
808 811 * stop running. The target thread should check this variable
809 812 * regularly, and return from its run method in an orderly fashion
810 813 * if the variable indicates that it is to stop running. If the
811 814 * target thread waits for long periods (on a condition variable,
812 815 * for example), the <code>interrupt</code> method should be used to
813 816 * interrupt the wait.
814 817 * For more information, see
815 818 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
816 819 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
817 820 */
818 821 @Deprecated
819 822 public final void stop() {
820 823 // If the thread is already dead, return.
821 824 // A zero status value corresponds to "NEW".
822 825 if ((threadStatus != 0) && !isAlive()) {
823 826 return;
824 827 }
825 828 stop1(new ThreadDeath());
826 829 }
827 830
828 831 /**
829 832 * Forces the thread to stop executing.
830 833 * <p>
831 834 * If there is a security manager installed, the <code>checkAccess</code>
832 835 * method of this thread is called, which may result in a
833 836 * <code>SecurityException</code> being raised (in the current thread).
834 837 * <p>
835 838 * If this thread is different from the current thread (that is, the current
836 839 * thread is trying to stop a thread other than itself) or
837 840 * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
838 841 * security manager's <code>checkPermission</code> method (with the
839 842 * <code>RuntimePermission("stopThread")</code> argument) is called in
840 843 * addition.
841 844 * Again, this may result in throwing a
842 845 * <code>SecurityException</code> (in the current thread).
843 846 * <p>
844 847 * If the argument <code>obj</code> is null, a
845 848 * <code>NullPointerException</code> is thrown (in the current thread).
846 849 * <p>
847 850 * The thread represented by this thread is forced to stop
848 851 * whatever it is doing abnormally and to throw the
849 852 * <code>Throwable</code> object <code>obj</code> as an exception. This
850 853 * is an unusual action to take; normally, the <code>stop</code> method
851 854 * that takes no arguments should be used.
852 855 * <p>
853 856 * It is permitted to stop a thread that has not yet been started.
854 857 * If the thread is eventually started, it immediately terminates.
855 858 *
856 859 * @param obj the Throwable object to be thrown.
857 860 * @exception SecurityException if the current thread cannot modify
858 861 * this thread.
859 862 * @throws NullPointerException if obj is <tt>null</tt>.
860 863 * @see #interrupt()
861 864 * @see #checkAccess()
862 865 * @see #run()
863 866 * @see #start()
864 867 * @see #stop()
865 868 * @see SecurityManager#checkAccess(Thread)
866 869 * @see SecurityManager#checkPermission
867 870 * @deprecated This method is inherently unsafe. See {@link #stop()}
868 871 * for details. An additional danger of this
869 872 * method is that it may be used to generate exceptions that the
870 873 * target thread is unprepared to handle (including checked
871 874 * exceptions that the thread could not possibly throw, were it
872 875 * not for this method).
873 876 * For more information, see
874 877 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
875 878 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
876 879 */
877 880 @Deprecated
878 881 public final synchronized void stop(Throwable obj) {
879 882 stop1(obj);
880 883 }
881 884
882 885 /**
883 886 * Common impl for stop() and stop(Throwable).
884 887 */
885 888 private final synchronized void stop1(Throwable th) {
886 889 SecurityManager security = System.getSecurityManager();
887 890 if (security != null) {
888 891 checkAccess();
889 892 if ((this != Thread.currentThread()) ||
890 893 (!(th instanceof ThreadDeath))) {
891 894 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
892 895 }
893 896 }
894 897 // A zero status value corresponds to "NEW"
895 898 if (threadStatus != 0) {
896 899 resume(); // Wake up thread if it was suspended; no-op otherwise
897 900 stop0(th);
898 901 } else {
899 902
900 903 // Must do the null arg check that the VM would do with stop0
901 904 if (th == null) {
902 905 throw new NullPointerException();
903 906 }
904 907
905 908 // Remember this stop attempt for if/when start is used
906 909 stopBeforeStart = true;
907 910 throwableFromStop = th;
908 911 }
909 912 }
910 913
911 914 /**
912 915 * Interrupts this thread.
913 916 *
914 917 * <p> Unless the current thread is interrupting itself, which is
915 918 * always permitted, the {@link #checkAccess() checkAccess} method
916 919 * of this thread is invoked, which may cause a {@link
917 920 * SecurityException} to be thrown.
918 921 *
919 922 * <p> If this thread is blocked in an invocation of the {@link
920 923 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
921 924 * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
922 925 * class, or of the {@link #join()}, {@link #join(long)}, {@link
923 926 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
924 927 * methods of this class, then its interrupt status will be cleared and it
925 928 * will receive an {@link InterruptedException}.
926 929 *
927 930 * <p> If this thread is blocked in an I/O operation upon an {@link
928 931 * java.nio.channels.InterruptibleChannel </code>interruptible
929 932 * channel<code>} then the channel will be closed, the thread's interrupt
930 933 * status will be set, and the thread will receive a {@link
931 934 * java.nio.channels.ClosedByInterruptException}.
932 935 *
933 936 * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
934 937 * then the thread's interrupt status will be set and it will return
935 938 * immediately from the selection operation, possibly with a non-zero
936 939 * value, just as if the selector's {@link
937 940 * java.nio.channels.Selector#wakeup wakeup} method were invoked.
938 941 *
939 942 * <p> If none of the previous conditions hold then this thread's interrupt
940 943 * status will be set. </p>
941 944 *
942 945 * <p> Interrupting a thread that is not alive need not have any effect.
943 946 *
944 947 * @throws SecurityException
945 948 * if the current thread cannot modify this thread
946 949 *
947 950 * @revised 6.0
948 951 * @spec JSR-51
949 952 */
950 953 public void interrupt() {
951 954 if (this != Thread.currentThread())
952 955 checkAccess();
953 956
954 957 synchronized (blockerLock) {
955 958 Interruptible b = blocker;
956 959 if (b != null) {
957 960 interrupt0(); // Just to set the interrupt flag
958 961 b.interrupt();
959 962 return;
960 963 }
961 964 }
962 965 interrupt0();
963 966 }
964 967
965 968 /**
966 969 * Tests whether the current thread has been interrupted. The
967 970 * <i>interrupted status</i> of the thread is cleared by this method. In
968 971 * other words, if this method were to be called twice in succession, the
969 972 * second call would return false (unless the current thread were
970 973 * interrupted again, after the first call had cleared its interrupted
971 974 * status and before the second call had examined it).
972 975 *
973 976 * <p>A thread interruption ignored because a thread was not alive
974 977 * at the time of the interrupt will be reflected by this method
975 978 * returning false.
976 979 *
977 980 * @return <code>true</code> if the current thread has been interrupted;
978 981 * <code>false</code> otherwise.
979 982 * @see #isInterrupted()
980 983 * @revised 6.0
981 984 */
982 985 public static boolean interrupted() {
983 986 return currentThread().isInterrupted(true);
984 987 }
985 988
986 989 /**
987 990 * Tests whether this thread has been interrupted. The <i>interrupted
988 991 * status</i> of the thread is unaffected by this method.
989 992 *
990 993 * <p>A thread interruption ignored because a thread was not alive
991 994 * at the time of the interrupt will be reflected by this method
992 995 * returning false.
993 996 *
994 997 * @return <code>true</code> if this thread has been interrupted;
995 998 * <code>false</code> otherwise.
996 999 * @see #interrupted()
997 1000 * @revised 6.0
998 1001 */
999 1002 public boolean isInterrupted() {
1000 1003 return isInterrupted(false);
1001 1004 }
1002 1005
1003 1006 /**
1004 1007 * Tests if some Thread has been interrupted. The interrupted state
1005 1008 * is reset or not based on the value of ClearInterrupted that is
1006 1009 * passed.
1007 1010 */
1008 1011 private native boolean isInterrupted(boolean ClearInterrupted);
1009 1012
1010 1013 /**
1011 1014 * Throws {@link NoSuchMethodError}.
1012 1015 *
1013 1016 * @deprecated This method was originally designed to destroy this
1014 1017 * thread without any cleanup. Any monitors it held would have
1015 1018 * remained locked. However, the method was never implemented.
1016 1019 * If if were to be implemented, it would be deadlock-prone in
1017 1020 * much the manner of {@link #suspend}. If the target thread held
1018 1021 * a lock protecting a critical system resource when it was
1019 1022 * destroyed, no thread could ever access this resource again.
1020 1023 * If another thread ever attempted to lock this resource, deadlock
1021 1024 * would result. Such deadlocks typically manifest themselves as
1022 1025 * "frozen" processes. For more information, see
1023 1026 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
1024 1027 * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1025 1028 * @throws NoSuchMethodError always
1026 1029 */
1027 1030 @Deprecated
1028 1031 public void destroy() {
1029 1032 throw new NoSuchMethodError();
1030 1033 }
1031 1034
1032 1035 /**
1033 1036 * Tests if this thread is alive. A thread is alive if it has
1034 1037 * been started and has not yet died.
1035 1038 *
1036 1039 * @return <code>true</code> if this thread is alive;
1037 1040 * <code>false</code> otherwise.
1038 1041 */
1039 1042 public final native boolean isAlive();
1040 1043
1041 1044 /**
1042 1045 * Suspends this thread.
1043 1046 * <p>
1044 1047 * First, the <code>checkAccess</code> method of this thread is called
1045 1048 * with no arguments. This may result in throwing a
1046 1049 * <code>SecurityException </code>(in the current thread).
1047 1050 * <p>
1048 1051 * If the thread is alive, it is suspended and makes no further
1049 1052 * progress unless and until it is resumed.
1050 1053 *
1051 1054 * @exception SecurityException if the current thread cannot modify
1052 1055 * this thread.
1053 1056 * @see #checkAccess
1054 1057 * @deprecated This method has been deprecated, as it is
1055 1058 * inherently deadlock-prone. If the target thread holds a lock on the
1056 1059 * monitor protecting a critical system resource when it is suspended, no
1057 1060 * thread can access this resource until the target thread is resumed. If
1058 1061 * the thread that would resume the target thread attempts to lock this
1059 1062 * monitor prior to calling <code>resume</code>, deadlock results. Such
1060 1063 * deadlocks typically manifest themselves as "frozen" processes.
1061 1064 * For more information, see
1062 1065 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1063 1066 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1064 1067 */
1065 1068 @Deprecated
1066 1069 public final void suspend() {
1067 1070 checkAccess();
1068 1071 suspend0();
1069 1072 }
1070 1073
1071 1074 /**
1072 1075 * Resumes a suspended thread.
1073 1076 * <p>
1074 1077 * First, the <code>checkAccess</code> method of this thread is called
1075 1078 * with no arguments. This may result in throwing a
1076 1079 * <code>SecurityException</code> (in the current thread).
1077 1080 * <p>
1078 1081 * If the thread is alive but suspended, it is resumed and is
1079 1082 * permitted to make progress in its execution.
1080 1083 *
1081 1084 * @exception SecurityException if the current thread cannot modify this
1082 1085 * thread.
1083 1086 * @see #checkAccess
1084 1087 * @see #suspend()
1085 1088 * @deprecated This method exists solely for use with {@link #suspend},
1086 1089 * which has been deprecated because it is deadlock-prone.
1087 1090 * For more information, see
1088 1091 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1089 1092 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1090 1093 */
1091 1094 @Deprecated
1092 1095 public final void resume() {
1093 1096 checkAccess();
1094 1097 resume0();
1095 1098 }
1096 1099
1097 1100 /**
1098 1101 * Changes the priority of this thread.
1099 1102 * <p>
1100 1103 * First the <code>checkAccess</code> method of this thread is called
1101 1104 * with no arguments. This may result in throwing a
1102 1105 * <code>SecurityException</code>.
1103 1106 * <p>
1104 1107 * Otherwise, the priority of this thread is set to the smaller of
1105 1108 * the specified <code>newPriority</code> and the maximum permitted
1106 1109 * priority of the thread's thread group.
1107 1110 *
1108 1111 * @param newPriority priority to set this thread to
1109 1112 * @exception IllegalArgumentException If the priority is not in the
1110 1113 * range <code>MIN_PRIORITY</code> to
1111 1114 * <code>MAX_PRIORITY</code>.
1112 1115 * @exception SecurityException if the current thread cannot modify
1113 1116 * this thread.
1114 1117 * @see #getPriority
1115 1118 * @see #checkAccess()
1116 1119 * @see #getThreadGroup()
1117 1120 * @see #MAX_PRIORITY
1118 1121 * @see #MIN_PRIORITY
1119 1122 * @see ThreadGroup#getMaxPriority()
1120 1123 */
1121 1124 public final void setPriority(int newPriority) {
1122 1125 ThreadGroup g;
1123 1126 checkAccess();
1124 1127 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1125 1128 throw new IllegalArgumentException();
1126 1129 }
1127 1130 if((g = getThreadGroup()) != null) {
1128 1131 if (newPriority > g.getMaxPriority()) {
1129 1132 newPriority = g.getMaxPriority();
1130 1133 }
1131 1134 setPriority0(priority = newPriority);
1132 1135 }
1133 1136 }
1134 1137
1135 1138 /**
1136 1139 * Returns this thread's priority.
1137 1140 *
1138 1141 * @return this thread's priority.
1139 1142 * @see #setPriority
1140 1143 */
1141 1144 public final int getPriority() {
1142 1145 return priority;
1143 1146 }
1144 1147
1145 1148 /**
1146 1149 * Changes the name of this thread to be equal to the argument
1147 1150 * <code>name</code>.
1148 1151 * <p>
1149 1152 * First the <code>checkAccess</code> method of this thread is called
1150 1153 * with no arguments. This may result in throwing a
1151 1154 * <code>SecurityException</code>.
1152 1155 *
1153 1156 * @param name the new name for this thread.
1154 1157 * @exception SecurityException if the current thread cannot modify this
1155 1158 * thread.
1156 1159 * @see #getName
1157 1160 * @see #checkAccess()
1158 1161 */
1159 1162 public final void setName(String name) {
1160 1163 checkAccess();
1161 1164 this.name = name.toCharArray();
1162 1165 }
1163 1166
1164 1167 /**
1165 1168 * Returns this thread's name.
1166 1169 *
1167 1170 * @return this thread's name.
1168 1171 * @see #setName(String)
1169 1172 */
1170 1173 public final String getName() {
1171 1174 return String.valueOf(name);
1172 1175 }
1173 1176
1174 1177 /**
1175 1178 * Returns the thread group to which this thread belongs.
1176 1179 * This method returns null if this thread has died
1177 1180 * (been stopped).
1178 1181 *
1179 1182 * @return this thread's thread group.
1180 1183 */
1181 1184 public final ThreadGroup getThreadGroup() {
1182 1185 return group;
1183 1186 }
1184 1187
1185 1188 /**
1186 1189 * Returns an estimate of the number of active threads in the current
1187 1190 * thread's {@linkplain java.lang.ThreadGroup thread group} and its
1188 1191 * subgroups. Recursively iterates over all subgroups in the current
1189 1192 * thread's thread group.
1190 1193 *
1191 1194 * <p> The value returned is only an estimate because the number of
1192 1195 * threads may change dynamically while this method traverses internal
1193 1196 * data structures, and might be affected by the presence of certain
1194 1197 * system threads. This method is intended primarily for debugging
1195 1198 * and monitoring purposes.
1196 1199 *
1197 1200 * @return an estimate of the number of active threads in the current
1198 1201 * thread's thread group and in any other thread group that
1199 1202 * has the current thread's thread group as an ancestor
1200 1203 */
1201 1204 public static int activeCount() {
1202 1205 return currentThread().getThreadGroup().activeCount();
1203 1206 }
1204 1207
1205 1208 /**
1206 1209 * Copies into the specified array every active thread in the current
1207 1210 * thread's thread group and its subgroups. This method simply
1208 1211 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1209 1212 * method of the current thread's thread group.
1210 1213 *
1211 1214 * <p> An application might use the {@linkplain #activeCount activeCount}
1212 1215 * method to get an estimate of how big the array should be, however
1213 1216 * <i>if the array is too short to hold all the threads, the extra threads
1214 1217 * are silently ignored.</i> If it is critical to obtain every active
1215 1218 * thread in the current thread's thread group and its subgroups, the
1216 1219 * invoker should verify that the returned int value is strictly less
1217 1220 * than the length of {@code tarray}.
1218 1221 *
1219 1222 * <p> Due to the inherent race condition in this method, it is recommended
1220 1223 * that the method only be used for debugging and monitoring purposes.
1221 1224 *
1222 1225 * @param tarray
1223 1226 * an array into which to put the list of threads
1224 1227 *
1225 1228 * @return the number of threads put into the array
1226 1229 *
1227 1230 * @throws SecurityException
1228 1231 * if {@link java.lang.ThreadGroup#checkAccess} determines that
1229 1232 * the current thread cannot access its thread group
1230 1233 */
1231 1234 public static int enumerate(Thread tarray[]) {
1232 1235 return currentThread().getThreadGroup().enumerate(tarray);
1233 1236 }
1234 1237
1235 1238 /**
1236 1239 * Counts the number of stack frames in this thread. The thread must
1237 1240 * be suspended.
1238 1241 *
1239 1242 * @return the number of stack frames in this thread.
1240 1243 * @exception IllegalThreadStateException if this thread is not
1241 1244 * suspended.
1242 1245 * @deprecated The definition of this call depends on {@link #suspend},
1243 1246 * which is deprecated. Further, the results of this call
1244 1247 * were never well-defined.
1245 1248 */
1246 1249 @Deprecated
1247 1250 public native int countStackFrames();
1248 1251
1249 1252 /**
1250 1253 * Waits at most {@code millis} milliseconds for this thread to
1251 1254 * die. A timeout of {@code 0} means to wait forever.
1252 1255 *
1253 1256 * <p> This implementation uses a loop of {@code this.wait} calls
1254 1257 * conditioned on {@code this.isAlive}. As a thread terminates the
1255 1258 * {@code this.notifyAll} method is invoked. It is recommended that
1256 1259 * applications not use {@code wait}, {@code notify}, or
1257 1260 * {@code notifyAll} on {@code Thread} instances.
1258 1261 *
1259 1262 * @param millis
1260 1263 * the time to wait in milliseconds
1261 1264 *
1262 1265 * @throws IllegalArgumentException
1263 1266 * if the value of {@code millis} is negative
1264 1267 *
1265 1268 * @throws InterruptedException
1266 1269 * if any thread has interrupted the current thread. The
1267 1270 * <i>interrupted status</i> of the current thread is
1268 1271 * cleared when this exception is thrown.
1269 1272 */
1270 1273 public final synchronized void join(long millis)
1271 1274 throws InterruptedException {
1272 1275 long base = System.currentTimeMillis();
1273 1276 long now = 0;
1274 1277
1275 1278 if (millis < 0) {
1276 1279 throw new IllegalArgumentException("timeout value is negative");
1277 1280 }
1278 1281
1279 1282 if (millis == 0) {
1280 1283 while (isAlive()) {
1281 1284 wait(0);
1282 1285 }
1283 1286 } else {
1284 1287 while (isAlive()) {
1285 1288 long delay = millis - now;
1286 1289 if (delay <= 0) {
1287 1290 break;
1288 1291 }
1289 1292 wait(delay);
1290 1293 now = System.currentTimeMillis() - base;
1291 1294 }
1292 1295 }
1293 1296 }
1294 1297
1295 1298 /**
1296 1299 * Waits at most {@code millis} milliseconds plus
1297 1300 * {@code nanos} nanoseconds for this thread to die.
1298 1301 *
1299 1302 * <p> This implementation uses a loop of {@code this.wait} calls
1300 1303 * conditioned on {@code this.isAlive}. As a thread terminates the
1301 1304 * {@code this.notifyAll} method is invoked. It is recommended that
1302 1305 * applications not use {@code wait}, {@code notify}, or
1303 1306 * {@code notifyAll} on {@code Thread} instances.
1304 1307 *
1305 1308 * @param millis
1306 1309 * the time to wait in milliseconds
1307 1310 *
1308 1311 * @param nanos
1309 1312 * {@code 0-999999} additional nanoseconds to wait
1310 1313 *
1311 1314 * @throws IllegalArgumentException
1312 1315 * if the value of {@code millis} is negative, or the value
1313 1316 * of {@code nanos} is not in the range {@code 0-999999}
1314 1317 *
1315 1318 * @throws InterruptedException
1316 1319 * if any thread has interrupted the current thread. The
1317 1320 * <i>interrupted status</i> of the current thread is
1318 1321 * cleared when this exception is thrown.
1319 1322 */
1320 1323 public final synchronized void join(long millis, int nanos)
1321 1324 throws InterruptedException {
1322 1325
1323 1326 if (millis < 0) {
1324 1327 throw new IllegalArgumentException("timeout value is negative");
1325 1328 }
1326 1329
1327 1330 if (nanos < 0 || nanos > 999999) {
1328 1331 throw new IllegalArgumentException(
1329 1332 "nanosecond timeout value out of range");
1330 1333 }
1331 1334
1332 1335 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
1333 1336 millis++;
1334 1337 }
1335 1338
1336 1339 join(millis);
1337 1340 }
1338 1341
1339 1342 /**
1340 1343 * Waits for this thread to die.
1341 1344 *
1342 1345 * <p> An invocation of this method behaves in exactly the same
1343 1346 * way as the invocation
1344 1347 *
1345 1348 * <blockquote>
1346 1349 * {@linkplain #join(long) join}{@code (0)}
1347 1350 * </blockquote>
1348 1351 *
1349 1352 * @throws InterruptedException
1350 1353 * if any thread has interrupted the current thread. The
1351 1354 * <i>interrupted status</i> of the current thread is
1352 1355 * cleared when this exception is thrown.
1353 1356 */
1354 1357 public final void join() throws InterruptedException {
1355 1358 join(0);
1356 1359 }
1357 1360
1358 1361 /**
1359 1362 * Prints a stack trace of the current thread to the standard error stream.
1360 1363 * This method is used only for debugging.
1361 1364 *
1362 1365 * @see Throwable#printStackTrace()
1363 1366 */
1364 1367 public static void dumpStack() {
1365 1368 new Exception("Stack trace").printStackTrace();
1366 1369 }
1367 1370
1368 1371 /**
1369 1372 * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1370 1373 * or a user thread. The Java Virtual Machine exits when the only
1371 1374 * threads running are all daemon threads.
1372 1375 *
1373 1376 * <p> This method must be invoked before the thread is started.
1374 1377 *
1375 1378 * @param on
1376 1379 * if {@code true}, marks this thread as a daemon thread
1377 1380 *
1378 1381 * @throws IllegalThreadStateException
1379 1382 * if this thread is {@linkplain #isAlive alive}
1380 1383 *
1381 1384 * @throws SecurityException
1382 1385 * if {@link #checkAccess} determines that the current
1383 1386 * thread cannot modify this thread
1384 1387 */
1385 1388 public final void setDaemon(boolean on) {
1386 1389 checkAccess();
1387 1390 if (isAlive()) {
1388 1391 throw new IllegalThreadStateException();
1389 1392 }
1390 1393 daemon = on;
1391 1394 }
1392 1395
1393 1396 /**
1394 1397 * Tests if this thread is a daemon thread.
1395 1398 *
1396 1399 * @return <code>true</code> if this thread is a daemon thread;
1397 1400 * <code>false</code> otherwise.
1398 1401 * @see #setDaemon(boolean)
1399 1402 */
1400 1403 public final boolean isDaemon() {
1401 1404 return daemon;
1402 1405 }
1403 1406
1404 1407 /**
1405 1408 * Determines if the currently running thread has permission to
1406 1409 * modify this thread.
1407 1410 * <p>
1408 1411 * If there is a security manager, its <code>checkAccess</code> method
1409 1412 * is called with this thread as its argument. This may result in
1410 1413 * throwing a <code>SecurityException</code>.
1411 1414 *
1412 1415 * @exception SecurityException if the current thread is not allowed to
1413 1416 * access this thread.
1414 1417 * @see SecurityManager#checkAccess(Thread)
1415 1418 */
1416 1419 public final void checkAccess() {
1417 1420 SecurityManager security = System.getSecurityManager();
1418 1421 if (security != null) {
1419 1422 security.checkAccess(this);
1420 1423 }
1421 1424 }
1422 1425
1423 1426 /**
1424 1427 * Returns a string representation of this thread, including the
1425 1428 * thread's name, priority, and thread group.
1426 1429 *
1427 1430 * @return a string representation of this thread.
1428 1431 */
1429 1432 public String toString() {
1430 1433 ThreadGroup group = getThreadGroup();
1431 1434 if (group != null) {
1432 1435 return "Thread[" + getName() + "," + getPriority() + "," +
1433 1436 group.getName() + "]";
1434 1437 } else {
1435 1438 return "Thread[" + getName() + "," + getPriority() + "," +
1436 1439 "" + "]";
1437 1440 }
1438 1441 }
1439 1442
1440 1443 /**
1441 1444 * Returns the context ClassLoader for this Thread. The context
1442 1445 * ClassLoader is provided by the creator of the thread for use
1443 1446 * by code running in this thread when loading classes and resources.
1444 1447 * If not {@linkplain #setContextClassLoader set}, the default is the
1445 1448 * ClassLoader context of the parent Thread. The context ClassLoader of the
1446 1449 * primordial thread is typically set to the class loader used to load the
1447 1450 * application.
1448 1451 *
1449 1452 * <p>If a security manager is present, and the invoker's class loader is not
1450 1453 * {@code null} and is not the same as or an ancestor of the context class
1451 1454 * loader, then this method invokes the security manager's {@link
1452 1455 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1453 1456 * method with a {@link RuntimePermission RuntimePermission}{@code
1454 1457 * ("getClassLoader")} permission to verify that retrieval of the context
1455 1458 * class loader is permitted.
1456 1459 *
1457 1460 * @return the context ClassLoader for this Thread, or {@code null}
1458 1461 * indicating the system class loader (or, failing that, the
1459 1462 * bootstrap class loader)
1460 1463 *
1461 1464 * @throws SecurityException
1462 1465 * if the current thread cannot get the context ClassLoader
1463 1466 *
1464 1467 * @since 1.2
1465 1468 */
1466 1469 public ClassLoader getContextClassLoader() {
1467 1470 if (contextClassLoader == null)
1468 1471 return null;
1469 1472 SecurityManager sm = System.getSecurityManager();
1470 1473 if (sm != null) {
1471 1474 ClassLoader ccl = ClassLoader.getCallerClassLoader();
1472 1475 if (ccl != null && ccl != contextClassLoader &&
1473 1476 !contextClassLoader.isAncestor(ccl)) {
1474 1477 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1475 1478 }
1476 1479 }
1477 1480 return contextClassLoader;
1478 1481 }
1479 1482
1480 1483 /**
1481 1484 * Sets the context ClassLoader for this Thread. The context
1482 1485 * ClassLoader can be set when a thread is created, and allows
1483 1486 * the creator of the thread to provide the appropriate class loader,
1484 1487 * through {@code getContextClassLoader}, to code running in the thread
1485 1488 * when loading classes and resources.
1486 1489 *
1487 1490 * <p>If a security manager is present, its {@link
1488 1491 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1489 1492 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1490 1493 * ("setContextClassLoader")} permission to see if setting the context
1491 1494 * ClassLoader is permitted.
1492 1495 *
1493 1496 * @param cl
1494 1497 * the context ClassLoader for this Thread, or null indicating the
1495 1498 * system class loader (or, failing that, the bootstrap class loader)
1496 1499 *
1497 1500 * @throws SecurityException
1498 1501 * if the current thread cannot set the context ClassLoader
1499 1502 *
1500 1503 * @since 1.2
1501 1504 */
1502 1505 public void setContextClassLoader(ClassLoader cl) {
1503 1506 SecurityManager sm = System.getSecurityManager();
1504 1507 if (sm != null) {
1505 1508 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
1506 1509 }
1507 1510 contextClassLoader = cl;
1508 1511 }
1509 1512
1510 1513 /**
1511 1514 * Returns <tt>true</tt> if and only if the current thread holds the
1512 1515 * monitor lock on the specified object.
1513 1516 *
1514 1517 * <p>This method is designed to allow a program to assert that
1515 1518 * the current thread already holds a specified lock:
1516 1519 * <pre>
1517 1520 * assert Thread.holdsLock(obj);
1518 1521 * </pre>
1519 1522 *
1520 1523 * @param obj the object on which to test lock ownership
1521 1524 * @throws NullPointerException if obj is <tt>null</tt>
1522 1525 * @return <tt>true</tt> if the current thread holds the monitor lock on
1523 1526 * the specified object.
1524 1527 * @since 1.4
1525 1528 */
1526 1529 public static native boolean holdsLock(Object obj);
1527 1530
1528 1531 private static final StackTraceElement[] EMPTY_STACK_TRACE
1529 1532 = new StackTraceElement[0];
1530 1533
1531 1534 /**
1532 1535 * Returns an array of stack trace elements representing the stack dump
1533 1536 * of this thread. This method will return a zero-length array if
1534 1537 * this thread has not started, has started but has not yet been
1535 1538 * scheduled to run by the system, or has terminated.
1536 1539 * If the returned array is of non-zero length then the first element of
1537 1540 * the array represents the top of the stack, which is the most recent
1538 1541 * method invocation in the sequence. The last element of the array
1539 1542 * represents the bottom of the stack, which is the least recent method
1540 1543 * invocation in the sequence.
1541 1544 *
1542 1545 * <p>If there is a security manager, and this thread is not
1543 1546 * the current thread, then the security manager's
1544 1547 * <tt>checkPermission</tt> method is called with a
1545 1548 * <tt>RuntimePermission("getStackTrace")</tt> permission
1546 1549 * to see if it's ok to get the stack trace.
1547 1550 *
1548 1551 * <p>Some virtual machines may, under some circumstances, omit one
1549 1552 * or more stack frames from the stack trace. In the extreme case,
1550 1553 * a virtual machine that has no stack trace information concerning
1551 1554 * this thread is permitted to return a zero-length array from this
1552 1555 * method.
1553 1556 *
1554 1557 * @return an array of <tt>StackTraceElement</tt>,
1555 1558 * each represents one stack frame.
1556 1559 *
1557 1560 * @throws SecurityException
1558 1561 * if a security manager exists and its
1559 1562 * <tt>checkPermission</tt> method doesn't allow
1560 1563 * getting the stack trace of thread.
1561 1564 * @see SecurityManager#checkPermission
1562 1565 * @see RuntimePermission
1563 1566 * @see Throwable#getStackTrace
1564 1567 *
1565 1568 * @since 1.5
1566 1569 */
1567 1570 public StackTraceElement[] getStackTrace() {
1568 1571 if (this != Thread.currentThread()) {
1569 1572 // check for getStackTrace permission
1570 1573 SecurityManager security = System.getSecurityManager();
1571 1574 if (security != null) {
1572 1575 security.checkPermission(
1573 1576 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1574 1577 }
1575 1578 // optimization so we do not call into the vm for threads that
1576 1579 // have not yet started or have terminated
1577 1580 if (!isAlive()) {
1578 1581 return EMPTY_STACK_TRACE;
1579 1582 }
1580 1583 StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
1581 1584 StackTraceElement[] stackTrace = stackTraceArray[0];
1582 1585 // a thread that was alive during the previous isAlive call may have
1583 1586 // since terminated, therefore not having a stacktrace.
1584 1587 if (stackTrace == null) {
1585 1588 stackTrace = EMPTY_STACK_TRACE;
1586 1589 }
1587 1590 return stackTrace;
1588 1591 } else {
1589 1592 // Don't need JVM help for current thread
1590 1593 return (new Exception()).getStackTrace();
1591 1594 }
1592 1595 }
1593 1596
1594 1597 /**
1595 1598 * Returns a map of stack traces for all live threads.
1596 1599 * The map keys are threads and each map value is an array of
1597 1600 * <tt>StackTraceElement</tt> that represents the stack dump
1598 1601 * of the corresponding <tt>Thread</tt>.
1599 1602 * The returned stack traces are in the format specified for
1600 1603 * the {@link #getStackTrace getStackTrace} method.
1601 1604 *
1602 1605 * <p>The threads may be executing while this method is called.
1603 1606 * The stack trace of each thread only represents a snapshot and
1604 1607 * each stack trace may be obtained at different time. A zero-length
1605 1608 * array will be returned in the map value if the virtual machine has
1606 1609 * no stack trace information about a thread.
1607 1610 *
1608 1611 * <p>If there is a security manager, then the security manager's
1609 1612 * <tt>checkPermission</tt> method is called with a
1610 1613 * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
1611 1614 * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
1612 1615 * to see if it is ok to get the stack trace of all threads.
1613 1616 *
1614 1617 * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1615 1618 * <tt>StackTraceElement</tt> that represents the stack trace of
1616 1619 * the corresponding thread.
1617 1620 *
1618 1621 * @throws SecurityException
1619 1622 * if a security manager exists and its
1620 1623 * <tt>checkPermission</tt> method doesn't allow
1621 1624 * getting the stack trace of thread.
1622 1625 * @see #getStackTrace
1623 1626 * @see SecurityManager#checkPermission
1624 1627 * @see RuntimePermission
1625 1628 * @see Throwable#getStackTrace
1626 1629 *
1627 1630 * @since 1.5
1628 1631 */
1629 1632 public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1630 1633 // check for getStackTrace permission
1631 1634 SecurityManager security = System.getSecurityManager();
1632 1635 if (security != null) {
1633 1636 security.checkPermission(
1634 1637 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1635 1638 security.checkPermission(
1636 1639 SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1637 1640 }
1638 1641
1639 1642 // Get a snapshot of the list of all threads
1640 1643 Thread[] threads = getThreads();
1641 1644 StackTraceElement[][] traces = dumpThreads(threads);
1642 1645 Map<Thread, StackTraceElement[]> m
1643 1646 = new HashMap<Thread, StackTraceElement[]>(threads.length);
1644 1647 for (int i = 0; i < threads.length; i++) {
1645 1648 StackTraceElement[] stackTrace = traces[i];
1646 1649 if (stackTrace != null) {
1647 1650 m.put(threads[i], stackTrace);
1648 1651 }
1649 1652 // else terminated so we don't put it in the map
1650 1653 }
1651 1654 return m;
1652 1655 }
1653 1656
1654 1657
1655 1658 private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
1656 1659 new RuntimePermission("enableContextClassLoaderOverride");
1657 1660
1658 1661 /** cache of subclass security audit results */
1659 1662 /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
1660 1663 * release */
1661 1664 private static class Caches {
1662 1665 /** cache of subclass security audit results */
1663 1666 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
1664 1667 new ConcurrentHashMap<WeakClassKey,Boolean>();
1665 1668
1666 1669 /** queue for WeakReferences to audited subclasses */
1667 1670 static final ReferenceQueue<Class<?>> subclassAuditsQueue =
1668 1671 new ReferenceQueue<Class<?>>();
1669 1672 }
1670 1673
1671 1674 /**
1672 1675 * Verifies that this (possibly subclass) instance can be constructed
1673 1676 * without violating security constraints: the subclass must not override
1674 1677 * security-sensitive non-final methods, or else the
1675 1678 * "enableContextClassLoaderOverride" RuntimePermission is checked.
1676 1679 */
1677 1680 private static boolean isCCLOverridden(Class cl) {
1678 1681 if (cl == Thread.class)
1679 1682 return false;
1680 1683
1681 1684 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1682 1685 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1683 1686 Boolean result = Caches.subclassAudits.get(key);
1684 1687 if (result == null) {
1685 1688 result = Boolean.valueOf(auditSubclass(cl));
1686 1689 Caches.subclassAudits.putIfAbsent(key, result);
1687 1690 }
1688 1691
1689 1692 return result.booleanValue();
1690 1693 }
1691 1694
1692 1695 /**
1693 1696 * Performs reflective checks on given subclass to verify that it doesn't
1694 1697 * override security-sensitive non-final methods. Returns true if the
1695 1698 * subclass overrides any of the methods, false otherwise.
1696 1699 */
1697 1700 private static boolean auditSubclass(final Class subcl) {
1698 1701 Boolean result = AccessController.doPrivileged(
1699 1702 new PrivilegedAction<Boolean>() {
1700 1703 public Boolean run() {
1701 1704 for (Class cl = subcl;
1702 1705 cl != Thread.class;
1703 1706 cl = cl.getSuperclass())
1704 1707 {
1705 1708 try {
1706 1709 cl.getDeclaredMethod("getContextClassLoader", new Class[0]);
1707 1710 return Boolean.TRUE;
1708 1711 } catch (NoSuchMethodException ex) {
1709 1712 }
1710 1713 try {
1711 1714 Class[] params = {ClassLoader.class};
1712 1715 cl.getDeclaredMethod("setContextClassLoader", params);
1713 1716 return Boolean.TRUE;
1714 1717 } catch (NoSuchMethodException ex) {
1715 1718 }
1716 1719 }
1717 1720 return Boolean.FALSE;
1718 1721 }
1719 1722 }
1720 1723 );
1721 1724 return result.booleanValue();
1722 1725 }
1723 1726
1724 1727 private native static StackTraceElement[][] dumpThreads(Thread[] threads);
1725 1728 private native static Thread[] getThreads();
1726 1729
1727 1730 /**
1728 1731 * Returns the identifier of this Thread. The thread ID is a positive
1729 1732 * <tt>long</tt> number generated when this thread was created.
1730 1733 * The thread ID is unique and remains unchanged during its lifetime.
1731 1734 * When a thread is terminated, this thread ID may be reused.
1732 1735 *
1733 1736 * @return this thread's ID.
1734 1737 * @since 1.5
1735 1738 */
1736 1739 public long getId() {
1737 1740 return tid;
1738 1741 }
1739 1742
1740 1743 /**
1741 1744 * A thread state. A thread can be in one of the following states:
1742 1745 * <ul>
1743 1746 * <li>{@link #NEW}<br>
1744 1747 * A thread that has not yet started is in this state.
1745 1748 * </li>
1746 1749 * <li>{@link #RUNNABLE}<br>
1747 1750 * A thread executing in the Java virtual machine is in this state.
1748 1751 * </li>
1749 1752 * <li>{@link #BLOCKED}<br>
1750 1753 * A thread that is blocked waiting for a monitor lock
1751 1754 * is in this state.
1752 1755 * </li>
1753 1756 * <li>{@link #WAITING}<br>
1754 1757 * A thread that is waiting indefinitely for another thread to
1755 1758 * perform a particular action is in this state.
1756 1759 * </li>
1757 1760 * <li>{@link #TIMED_WAITING}<br>
1758 1761 * A thread that is waiting for another thread to perform an action
1759 1762 * for up to a specified waiting time is in this state.
1760 1763 * </li>
1761 1764 * <li>{@link #TERMINATED}<br>
1762 1765 * A thread that has exited is in this state.
1763 1766 * </li>
1764 1767 * </ul>
1765 1768 *
1766 1769 * <p>
1767 1770 * A thread can be in only one state at a given point in time.
1768 1771 * These states are virtual machine states which do not reflect
1769 1772 * any operating system thread states.
1770 1773 *
1771 1774 * @since 1.5
1772 1775 * @see #getState
1773 1776 */
1774 1777 public enum State {
1775 1778 /**
1776 1779 * Thread state for a thread which has not yet started.
1777 1780 */
1778 1781 NEW,
1779 1782
1780 1783 /**
1781 1784 * Thread state for a runnable thread. A thread in the runnable
1782 1785 * state is executing in the Java virtual machine but it may
1783 1786 * be waiting for other resources from the operating system
1784 1787 * such as processor.
1785 1788 */
1786 1789 RUNNABLE,
1787 1790
1788 1791 /**
1789 1792 * Thread state for a thread blocked waiting for a monitor lock.
1790 1793 * A thread in the blocked state is waiting for a monitor lock
1791 1794 * to enter a synchronized block/method or
1792 1795 * reenter a synchronized block/method after calling
1793 1796 * {@link Object#wait() Object.wait}.
1794 1797 */
1795 1798 BLOCKED,
1796 1799
1797 1800 /**
1798 1801 * Thread state for a waiting thread.
1799 1802 * A thread is in the waiting state due to calling one of the
1800 1803 * following methods:
1801 1804 * <ul>
1802 1805 * <li>{@link Object#wait() Object.wait} with no timeout</li>
1803 1806 * <li>{@link #join() Thread.join} with no timeout</li>
1804 1807 * <li>{@link LockSupport#park() LockSupport.park}</li>
1805 1808 * </ul>
1806 1809 *
1807 1810 * <p>A thread in the waiting state is waiting for another thread to
1808 1811 * perform a particular action.
1809 1812 *
1810 1813 * For example, a thread that has called <tt>Object.wait()</tt>
1811 1814 * on an object is waiting for another thread to call
1812 1815 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
1813 1816 * that object. A thread that has called <tt>Thread.join()</tt>
1814 1817 * is waiting for a specified thread to terminate.
1815 1818 */
1816 1819 WAITING,
1817 1820
1818 1821 /**
1819 1822 * Thread state for a waiting thread with a specified waiting time.
1820 1823 * A thread is in the timed waiting state due to calling one of
1821 1824 * the following methods with a specified positive waiting time:
1822 1825 * <ul>
1823 1826 * <li>{@link #sleep Thread.sleep}</li>
1824 1827 * <li>{@link Object#wait(long) Object.wait} with timeout</li>
1825 1828 * <li>{@link #join(long) Thread.join} with timeout</li>
1826 1829 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1827 1830 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1828 1831 * </ul>
1829 1832 */
1830 1833 TIMED_WAITING,
1831 1834
1832 1835 /**
1833 1836 * Thread state for a terminated thread.
1834 1837 * The thread has completed execution.
1835 1838 */
1836 1839 TERMINATED;
1837 1840 }
1838 1841
1839 1842 /**
1840 1843 * Returns the state of this thread.
1841 1844 * This method is designed for use in monitoring of the system state,
1842 1845 * not for synchronization control.
1843 1846 *
1844 1847 * @return this thread's state.
1845 1848 * @since 1.5
1846 1849 */
1847 1850 public State getState() {
1848 1851 // get current thread state
1849 1852 return sun.misc.VM.toThreadState(threadStatus);
1850 1853 }
1851 1854
1852 1855 // Added in JSR-166
1853 1856
1854 1857 /**
1855 1858 * Interface for handlers invoked when a <tt>Thread</tt> abruptly
1856 1859 * terminates due to an uncaught exception.
1857 1860 * <p>When a thread is about to terminate due to an uncaught exception
1858 1861 * the Java Virtual Machine will query the thread for its
1859 1862 * <tt>UncaughtExceptionHandler</tt> using
1860 1863 * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1861 1864 * <tt>uncaughtException</tt> method, passing the thread and the
1862 1865 * exception as arguments.
1863 1866 * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
1864 1867 * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
1865 1868 * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
1866 1869 * has no
1867 1870 * special requirements for dealing with the exception, it can forward
1868 1871 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1869 1872 * default uncaught exception handler}.
1870 1873 *
1871 1874 * @see #setDefaultUncaughtExceptionHandler
1872 1875 * @see #setUncaughtExceptionHandler
1873 1876 * @see ThreadGroup#uncaughtException
1874 1877 * @since 1.5
1875 1878 */
1876 1879 public interface UncaughtExceptionHandler {
1877 1880 /**
1878 1881 * Method invoked when the given thread terminates due to the
1879 1882 * given uncaught exception.
1880 1883 * <p>Any exception thrown by this method will be ignored by the
1881 1884 * Java Virtual Machine.
1882 1885 * @param t the thread
1883 1886 * @param e the exception
1884 1887 */
1885 1888 void uncaughtException(Thread t, Throwable e);
1886 1889 }
1887 1890
1888 1891 // null unless explicitly set
1889 1892 private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1890 1893
1891 1894 // null unless explicitly set
1892 1895 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1893 1896
1894 1897 /**
1895 1898 * Set the default handler invoked when a thread abruptly terminates
1896 1899 * due to an uncaught exception, and no other handler has been defined
1897 1900 * for that thread.
1898 1901 *
1899 1902 * <p>Uncaught exception handling is controlled first by the thread, then
1900 1903 * by the thread's {@link ThreadGroup} object and finally by the default
1901 1904 * uncaught exception handler. If the thread does not have an explicit
1902 1905 * uncaught exception handler set, and the thread's thread group
1903 1906 * (including parent thread groups) does not specialize its
1904 1907 * <tt>uncaughtException</tt> method, then the default handler's
1905 1908 * <tt>uncaughtException</tt> method will be invoked.
1906 1909 * <p>By setting the default uncaught exception handler, an application
1907 1910 * can change the way in which uncaught exceptions are handled (such as
1908 1911 * logging to a specific device, or file) for those threads that would
1909 1912 * already accept whatever "default" behavior the system
1910 1913 * provided.
1911 1914 *
1912 1915 * <p>Note that the default uncaught exception handler should not usually
1913 1916 * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
1914 1917 * infinite recursion.
1915 1918 *
1916 1919 * @param eh the object to use as the default uncaught exception handler.
1917 1920 * If <tt>null</tt> then there is no default handler.
1918 1921 *
1919 1922 * @throws SecurityException if a security manager is present and it
1920 1923 * denies <tt>{@link RuntimePermission}
1921 1924 * ("setDefaultUncaughtExceptionHandler")</tt>
1922 1925 *
1923 1926 * @see #setUncaughtExceptionHandler
1924 1927 * @see #getUncaughtExceptionHandler
1925 1928 * @see ThreadGroup#uncaughtException
1926 1929 * @since 1.5
1927 1930 */
1928 1931 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1929 1932 SecurityManager sm = System.getSecurityManager();
1930 1933 if (sm != null) {
1931 1934 sm.checkPermission(
1932 1935 new RuntimePermission("setDefaultUncaughtExceptionHandler")
1933 1936 );
1934 1937 }
1935 1938
1936 1939 defaultUncaughtExceptionHandler = eh;
1937 1940 }
1938 1941
1939 1942 /**
1940 1943 * Returns the default handler invoked when a thread abruptly terminates
1941 1944 * due to an uncaught exception. If the returned value is <tt>null</tt>,
1942 1945 * there is no default.
1943 1946 * @since 1.5
1944 1947 * @see #setDefaultUncaughtExceptionHandler
1945 1948 */
1946 1949 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
1947 1950 return defaultUncaughtExceptionHandler;
1948 1951 }
1949 1952
1950 1953 /**
1951 1954 * Returns the handler invoked when this thread abruptly terminates
1952 1955 * due to an uncaught exception. If this thread has not had an
1953 1956 * uncaught exception handler explicitly set then this thread's
1954 1957 * <tt>ThreadGroup</tt> object is returned, unless this thread
1955 1958 * has terminated, in which case <tt>null</tt> is returned.
1956 1959 * @since 1.5
1957 1960 */
1958 1961 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1959 1962 return uncaughtExceptionHandler != null ?
1960 1963 uncaughtExceptionHandler : group;
1961 1964 }
1962 1965
1963 1966 /**
1964 1967 * Set the handler invoked when this thread abruptly terminates
1965 1968 * due to an uncaught exception.
1966 1969 * <p>A thread can take full control of how it responds to uncaught
1967 1970 * exceptions by having its uncaught exception handler explicitly set.
1968 1971 * If no such handler is set then the thread's <tt>ThreadGroup</tt>
1969 1972 * object acts as its handler.
1970 1973 * @param eh the object to use as this thread's uncaught exception
1971 1974 * handler. If <tt>null</tt> then this thread has no explicit handler.
1972 1975 * @throws SecurityException if the current thread is not allowed to
1973 1976 * modify this thread.
1974 1977 * @see #setDefaultUncaughtExceptionHandler
1975 1978 * @see ThreadGroup#uncaughtException
1976 1979 * @since 1.5
1977 1980 */
1978 1981 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1979 1982 checkAccess();
1980 1983 uncaughtExceptionHandler = eh;
1981 1984 }
1982 1985
1983 1986 /**
1984 1987 * Dispatch an uncaught exception to the handler. This method is
1985 1988 * intended to be called only by the JVM.
1986 1989 */
1987 1990 private void dispatchUncaughtException(Throwable e) {
1988 1991 getUncaughtExceptionHandler().uncaughtException(this, e);
1989 1992 }
1990 1993
1991 1994 /**
1992 1995 * Removes from the specified map any keys that have been enqueued
1993 1996 * on the specified reference queue.
1994 1997 */
1995 1998 static void processQueue(ReferenceQueue<Class<?>> queue,
1996 1999 ConcurrentMap<? extends
1997 2000 WeakReference<Class<?>>, ?> map)
1998 2001 {
1999 2002 Reference<? extends Class<?>> ref;
2000 2003 while((ref = queue.poll()) != null) {
2001 2004 map.remove(ref);
2002 2005 }
2003 2006 }
2004 2007
2005 2008 /**
2006 2009 * Weak key for Class objects.
2007 2010 **/
2008 2011 static class WeakClassKey extends WeakReference<Class<?>> {
2009 2012 /**
2010 2013 * saved value of the referent's identity hash code, to maintain
2011 2014 * a consistent hash code after the referent has been cleared
2012 2015 */
2013 2016 private final int hash;
2014 2017
2015 2018 /**
2016 2019 * Create a new WeakClassKey to the given object, registered
2017 2020 * with a queue.
2018 2021 */
2019 2022 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
2020 2023 super(cl, refQueue);
2021 2024 hash = System.identityHashCode(cl);
2022 2025 }
2023 2026
2024 2027 /**
2025 2028 * Returns the identity hash code of the original referent.
2026 2029 */
2027 2030 @Override
2028 2031 public int hashCode() {
2029 2032 return hash;
2030 2033 }
2031 2034
2032 2035 /**
2033 2036 * Returns true if the given object is this identical
2034 2037 * WeakClassKey instance, or, if this object's referent has not
2035 2038 * been cleared, if the given object is another WeakClassKey
2036 2039 * instance with the identical non-null referent as this one.
2037 2040 */
2038 2041 @Override
2039 2042 public boolean equals(Object obj) {
2040 2043 if (obj == this)
2041 2044 return true;
2042 2045
2043 2046 if (obj instanceof WeakClassKey) {
2044 2047 Object referent = get();
2045 2048 return (referent != null) &&
2046 2049 (referent == ((WeakClassKey) obj).get());
2047 2050 } else {
2048 2051 return false;
2049 2052 }
2050 2053 }
2051 2054 }
2052 2055
2053 2056 /* Some private helper methods */
2054 2057 private native void setPriority0(int newPriority);
2055 2058 private native void stop0(Object o);
2056 2059 private native void suspend0();
2057 2060 private native void resume0();
2058 2061 private native void interrupt0();
2059 2062 }
↓ open down ↓ |
1349 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX