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