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