1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 /* 18 * Copyright (C) 2008 The Android Open Source Project 19 * 20 * Licensed under the Apache License, Version 2.0 (the "License"); 21 * you may not use this file except in compliance with the License. 22 * You may obtain a copy of the License at 23 * 24 * http://www.apache.org/licenses/LICENSE-2.0 25 * 26 * Unless required by applicable law or agreed to in writing, software 27 * distributed under the License is distributed on an "AS IS" BASIS, 28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 * See the License for the specific language governing permissions and 30 * limitations under the License. 31 */ 32 33 package java.lang; 34 35 import dalvik.system.VMStack; 36 37 import java.security.AccessController; 38 import java.util.Map; 39 import java.util.HashMap; 40 41 import org.apache.harmony.security.fortress.SecurityUtils; 42 43 /** 44 * A {@code Thread} is a concurrent unit of execution. It has its own call stack 45 * for methods being invoked, their arguments and local variables. Each virtual 46 * machine instance has at least one main {@code Thread} running when it is 47 * started; typically, there are several others for housekeeping. The 48 * application might decide to launch additional {@code Thread}s for specific 49 * purposes. 50 * <p> 51 * {@code Thread}s in the same VM interact and synchronize by the use of shared 52 * objects and monitors associated with these objects. Synchronized methods and 53 * part of the API in {@link Object} also allow {@code Thread}s to cooperate. 54 * <p> 55 * There are basically two main ways of having a {@code Thread} execute 56 * application code. One is providing a new class that extends {@code Thread} 57 * and overriding its {@link #run()} method. The other is providing a new 58 * {@code Thread} instance with a {@link Runnable} object during its creation. 59 * In both cases, the {@link #start()} method must be called to actually execute 60 * the new {@code Thread}. 61 * <p> 62 * Each {@code Thread} has an integer priority that basically determines the 63 * amount of CPU time the {@code Thread} gets. It can be set using the 64 * {@link #setPriority(int)} method. A {@code Thread} can also be made a daemon, 65 * which makes it run in the background. The latter also affects VM termination 66 * behavior: the VM does not terminate automatically as long as there are 67 * non-daemon threads running. 68 * 69 * @see java.lang.Object 70 * @see java.lang.ThreadGroup 71 * 72 * @since Android 1.0 73 */ 74 public class Thread implements Runnable { 75 76 private static final int NANOS_PER_MILLI = 1000000; 77 78 /** Park states */ 79 private static class ParkState { 80 /** park state indicating unparked */ 81 private static final int UNPARKED = 1; 82 83 /** park state indicating preemptively unparked */ 84 private static final int PREEMPTIVELY_UNPARKED = 2; 85 86 /** park state indicating parked */ 87 private static final int PARKED = 3; 88 } 89 90 /** 91 * A representation of a thread's state. A given thread may only be in one 92 * state at a time. 93 * 94 * @since Android 1.0 95 */ 96 public enum State { 97 /** 98 * The thread has been created, but has never been started. 99 */ 100 NEW, 101 /** 102 * The thread may be run. 103 */ 104 RUNNABLE, 105 /** 106 * The thread is blocked and waiting for a lock. 107 */ 108 BLOCKED, 109 /** 110 * The thread is waiting. 111 */ 112 WAITING, 113 /** 114 * The thread is waiting for a specified amount of time. 115 */ 116 TIMED_WAITING, 117 /** 118 * The thread has been terminated. 119 */ 120 TERMINATED 121 } 122 123 /** 124 * The maximum priority value allowed for a thread. 125 * 126 * @since Android 1.0 127 */ 128 public final static int MAX_PRIORITY = 10; 129 130 /** 131 * The minimum priority value allowed for a thread. 132 * 133 * @since Android 1.0 134 */ 135 public final static int MIN_PRIORITY = 1; 136 137 /** 138 * The normal (default) priority value assigned to threads. 139 * 140 * @since Android 1.0 141 */ 142 public final static int NORM_PRIORITY = 5; 143 144 /* some of these are accessed directly by the VM; do not rename them */ 145 volatile VMThread vmThread; 146 volatile ThreadGroup group; 147 volatile boolean daemon; 148 volatile String name; 149 volatile int priority; 150 volatile long stackSize; 151 Runnable target; 152 private static int count = 0; 153 154 /** 155 * Holds the thread's ID. We simply count upwards, so 156 * each Thread has a unique ID. 157 */ 158 private long id; 159 160 /** 161 * Normal thread local values. 162 */ 163 ThreadLocal.Values localValues; 164 165 /** 166 * Inheritable thread local values. 167 */ 168 ThreadLocal.Values inheritableValues; 169 170 /** 171 * Holds the interrupt action for this Thread, if any. 172 * <p> 173 * This is required internally by NIO, so even if it looks like it's 174 * useless, don't delete it! 175 */ 176 private Runnable interruptAction; 177 178 /** 179 * Holds the class loader for this Thread, in case there is one. 180 */ 181 private ClassLoader contextClassLoader; 182 183 /** 184 * Holds the handler for uncaught exceptions in this Thread, 185 * in case there is one. 186 */ 187 private UncaughtExceptionHandler uncaughtHandler; 188 189 /** 190 * Holds the default handler for uncaught exceptions, in case there is one. 191 */ 192 private static UncaughtExceptionHandler defaultUncaughtHandler; 193 194 /** 195 * Reflects whether this Thread has already been started. A Thread 196 * can only be started once (no recycling). Also, we need it to deduce 197 * the proper Thread status. 198 */ 199 boolean hasBeenStarted = false; 200 201 /** the park state of the thread */ 202 private int parkState = ParkState.UNPARKED; 203 204 /** 205 * Constructs a new {@code Thread} with no {@code Runnable} object and a 206 * newly generated name. The new {@code Thread} will belong to the same 207 * {@code ThreadGroup} as the {@code Thread} calling this constructor. 208 * 209 * @see java.lang.ThreadGroup 210 * @see java.lang.Runnable 211 * 212 * @since Android 1.0 213 */ Thread()214 public Thread() { 215 create(null, null, null, 0); 216 } 217 218 /** 219 * Constructs a new {@code Thread} with a {@code Runnable} object and a 220 * newly generated name. The new {@code Thread} will belong to the same 221 * {@code ThreadGroup} as the {@code Thread} calling this constructor. 222 * 223 * @param runnable 224 * a {@code Runnable} whose method <code>run</code> will be 225 * executed by the new {@code Thread} 226 * 227 * @see java.lang.ThreadGroup 228 * @see java.lang.Runnable 229 * 230 * @since Android 1.0 231 */ Thread(Runnable runnable)232 public Thread(Runnable runnable) { 233 create(null, runnable, null, 0); 234 } 235 236 /** 237 * Constructs a new {@code Thread} with a {@code Runnable} object and name 238 * provided. The new {@code Thread} will belong to the same {@code 239 * ThreadGroup} as the {@code Thread} calling this constructor. 240 * 241 * @param runnable 242 * a {@code Runnable} whose method <code>run</code> will be 243 * executed by the new {@code Thread} 244 * @param threadName 245 * the name for the {@code Thread} being created 246 * 247 * @see java.lang.ThreadGroup 248 * @see java.lang.Runnable 249 * 250 * @since Android 1.0 251 */ Thread(Runnable runnable, String threadName)252 public Thread(Runnable runnable, String threadName) { 253 if (threadName == null) { 254 throw new NullPointerException(); 255 } 256 257 create(null, runnable, threadName, 0); 258 } 259 260 /** 261 * Constructs a new {@code Thread} with no {@code Runnable} object and the 262 * name provided. The new {@code Thread} will belong to the same {@code 263 * ThreadGroup} as the {@code Thread} calling this constructor. 264 * 265 * @param threadName 266 * the name for the {@code Thread} being created 267 * 268 * @see java.lang.ThreadGroup 269 * @see java.lang.Runnable 270 * 271 * @since Android 1.0 272 */ Thread(String threadName)273 public Thread(String threadName) { 274 if (threadName == null) { 275 throw new NullPointerException(); 276 } 277 278 create(null, null, threadName, 0); 279 } 280 281 /** 282 * Constructs a new {@code Thread} with a {@code Runnable} object and a 283 * newly generated name. The new {@code Thread} will belong to the {@code 284 * ThreadGroup} passed as parameter. 285 * 286 * @param group 287 * {@code ThreadGroup} to which the new {@code Thread} will 288 * belong 289 * @param runnable 290 * a {@code Runnable} whose method <code>run</code> will be 291 * executed by the new {@code Thread} 292 * @throws SecurityException 293 * if <code>group.checkAccess()</code> fails with a 294 * SecurityException 295 * @throws IllegalThreadStateException 296 * if <code>group.destroy()</code> has already been done 297 * @see java.lang.ThreadGroup 298 * @see java.lang.Runnable 299 * @see java.lang.SecurityException 300 * @see java.lang.SecurityManager 301 * 302 * @since Android 1.0 303 */ Thread(ThreadGroup group, Runnable runnable)304 public Thread(ThreadGroup group, Runnable runnable) { 305 create(group, runnable, null, 0); 306 } 307 308 /** 309 * Constructs a new {@code Thread} with a {@code Runnable} object, the given 310 * name and belonging to the {@code ThreadGroup} passed as parameter. 311 * 312 * @param group 313 * ThreadGroup to which the new {@code Thread} will belong 314 * @param runnable 315 * a {@code Runnable} whose method <code>run</code> will be 316 * executed by the new {@code Thread} 317 * @param threadName 318 * the name for the {@code Thread} being created 319 * @throws SecurityException 320 * if <code>group.checkAccess()</code> fails with a 321 * SecurityException 322 * @throws IllegalThreadStateException 323 * if <code>group.destroy()</code> has already been done 324 * @see java.lang.ThreadGroup 325 * @see java.lang.Runnable 326 * @see java.lang.SecurityException 327 * @see java.lang.SecurityManager 328 * 329 * @since Android 1.0 330 */ Thread(ThreadGroup group, Runnable runnable, String threadName)331 public Thread(ThreadGroup group, Runnable runnable, String threadName) { 332 if (threadName == null) { 333 throw new NullPointerException(); 334 } 335 336 create(group, runnable, threadName, 0); 337 } 338 339 /** 340 * Constructs a new {@code Thread} with no {@code Runnable} object, the 341 * given name and belonging to the {@code ThreadGroup} passed as parameter. 342 * 343 * @param group 344 * {@code ThreadGroup} to which the new {@code Thread} will belong 345 * @param threadName 346 * the name for the {@code Thread} being created 347 * @throws SecurityException 348 * if <code>group.checkAccess()</code> fails with a 349 * SecurityException 350 * @throws IllegalThreadStateException 351 * if <code>group.destroy()</code> has already been done 352 * @see java.lang.ThreadGroup 353 * @see java.lang.Runnable 354 * @see java.lang.SecurityException 355 * @see java.lang.SecurityManager 356 * 357 * @since Android 1.0 358 */ Thread(ThreadGroup group, String threadName)359 public Thread(ThreadGroup group, String threadName) { 360 if (threadName == null) { 361 throw new NullPointerException(); 362 } 363 364 create(group, null, threadName, 0); 365 } 366 367 /** 368 * Constructs a new {@code Thread} with a {@code Runnable} object, the given 369 * name and belonging to the {@code ThreadGroup} passed as parameter. 370 * 371 * @param group 372 * {@code ThreadGroup} to which the new {@code Thread} will 373 * belong 374 * @param runnable 375 * a {@code Runnable} whose method <code>run</code> will be 376 * executed by the new {@code Thread} 377 * @param threadName 378 * the name for the {@code Thread} being created 379 * @param stackSize 380 * a stack size for the new {@code Thread}. This has a highly 381 * platform-dependent interpretation. It may even be ignored 382 * completely. 383 * @throws SecurityException 384 * if <code>group.checkAccess()</code> fails with a 385 * SecurityException 386 * @throws IllegalThreadStateException 387 * if <code>group.destroy()</code> has already been done 388 * @see java.lang.ThreadGroup 389 * @see java.lang.Runnable 390 * @see java.lang.SecurityException 391 * @see java.lang.SecurityManager 392 * 393 * @since Android 1.0 394 */ Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize)395 public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { 396 if (threadName == null) { 397 throw new NullPointerException(); 398 } 399 create(group, runnable, threadName, stackSize); 400 } 401 402 /** 403 * Package-scope method invoked by Dalvik VM to create "internal" 404 * threads or attach threads created externally. 405 * 406 * Don't call Thread.currentThread(), since there may not be such 407 * a thing (e.g. for Main). 408 */ Thread(ThreadGroup group, String name, int priority, boolean daemon)409 Thread(ThreadGroup group, String name, int priority, boolean daemon) { 410 synchronized (Thread.class) { 411 id = ++Thread.count; 412 } 413 414 if (name == null) { 415 this.name = "Thread-" + id; 416 } else 417 this.name = name; 418 419 if (group == null) { 420 throw new InternalError("group not specified"); 421 } 422 423 this.group = group; 424 425 this.target = null; 426 this.stackSize = 0; 427 this.priority = priority; 428 this.daemon = daemon; 429 430 /* add ourselves to our ThreadGroup of choice */ 431 this.group.addThread(this); 432 } 433 434 /** 435 * Initializes a new, existing Thread object with a runnable object, 436 * the given name and belonging to the ThreadGroup passed as parameter. 437 * This is the method that the several public constructors delegate their 438 * work to. 439 * 440 * @param group ThreadGroup to which the new Thread will belong 441 * @param runnable a java.lang.Runnable whose method <code>run</code> will 442 * be executed by the new Thread 443 * @param threadName Name for the Thread being created 444 * @param stackSize Platform dependent stack size 445 * @throws SecurityException if <code>group.checkAccess()</code> fails 446 * with a SecurityException 447 * @throws IllegalThreadStateException if <code>group.destroy()</code> has 448 * already been done 449 * @see java.lang.ThreadGroup 450 * @see java.lang.Runnable 451 * @see java.lang.SecurityException 452 * @see java.lang.SecurityManager 453 */ create(ThreadGroup group, Runnable runnable, String threadName, long stackSize)454 private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { 455 SecurityManager smgr = System.getSecurityManager(); 456 if (smgr != null) { 457 if (group == null) { 458 group = smgr.getThreadGroup(); 459 } 460 461 /* 462 * Freaky security requirement: If the Thread's class is actually 463 * a subclass of Thread and it tries to override either 464 * getContextClassLoader() or setContextClassLoader(), the 465 * SecurityManager has to allow this. 466 */ 467 if (getClass() != Thread.class) { 468 Class[] signature = new Class[] { ClassLoader.class }; 469 470 try { 471 getClass().getDeclaredMethod("getContextClassLoader", signature); 472 smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride")); 473 } catch (NoSuchMethodException ex) { 474 // Ignore. Just interested in the method's existence. 475 } 476 477 try { 478 getClass().getDeclaredMethod("setContextClassLoader", signature); 479 smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride")); 480 } catch (NoSuchMethodException ex) { 481 // Ignore. Just interested in the method's existence. 482 } 483 } 484 } 485 486 Thread currentThread = Thread.currentThread(); 487 if (group == null) { 488 group = currentThread.getThreadGroup(); 489 } 490 491 group.checkAccess(); 492 if (group.isDestroyed()) { 493 throw new IllegalThreadStateException("Group already destroyed"); 494 } 495 496 this.group = group; 497 498 synchronized (Thread.class) { 499 id = ++Thread.count; 500 } 501 502 if (threadName == null) { 503 this.name = "Thread-" + id; 504 } else { 505 this.name = threadName; 506 } 507 508 this.target = runnable; 509 this.stackSize = stackSize; 510 511 this.priority = currentThread.getPriority(); 512 513 this.contextClassLoader = currentThread.contextClassLoader; 514 515 // Transfer over InheritableThreadLocals. 516 if (currentThread.inheritableValues != null) { 517 inheritableValues 518 = new ThreadLocal.Values(currentThread.inheritableValues); 519 } 520 521 // store current AccessControlContext as inherited context for this thread 522 SecurityUtils.putContext(this, AccessController.getContext()); 523 524 // add ourselves to our ThreadGroup of choice 525 this.group.addThread(this); 526 } 527 528 /** 529 * Returns the number of active {@code Thread}s in the running {@code 530 * Thread}'s group and its subgroups. 531 * 532 * @return the number of {@code Thread}s 533 * 534 * @since Android 1.0 535 */ activeCount()536 public static int activeCount() { 537 return currentThread().getThreadGroup().activeCount(); 538 } 539 540 /** 541 * Is used for operations that require approval from a SecurityManager. If 542 * there's none installed, this method is a no-op. If there's a 543 * SecurityManager installed, {@link SecurityManager#checkAccess(Thread)} is 544 * called for that SecurityManager. 545 * 546 * @throws SecurityException 547 * if a SecurityManager is installed and it does not allow 548 * access to the Thread. 549 * 550 * @see java.lang.SecurityException 551 * @see java.lang.SecurityManager 552 * 553 * @since Android 1.0 554 */ checkAccess()555 public final void checkAccess() { 556 // Forwards the message to the SecurityManager (if there's one) passing 557 // the receiver as parameter 558 559 SecurityManager currentManager = System.getSecurityManager(); 560 if (currentManager != null) { 561 currentManager.checkAccess(this); 562 } 563 } 564 565 /** 566 * Returns the number of stack frames in this thread. 567 * 568 * @return Number of stack frames 569 * @deprecated The results of this call were never well defined. To make 570 * things worse, it would depend on whether the Thread was 571 * suspended or not, and suspend was deprecated too. 572 * 573 * @since Android 1.0 574 */ 575 @Deprecated countStackFrames()576 public int countStackFrames() { 577 return getStackTrace().length; 578 } 579 580 /** 581 * Returns the Thread of the caller, that is, the current Thread. 582 * 583 * @return the current Thread. 584 * 585 * @since Android 1.0 586 */ currentThread()587 public static Thread currentThread() { 588 return VMThread.currentThread(); 589 } 590 591 /** 592 * Destroys the receiver without any monitor cleanup. 593 * 594 * @deprecated Not implemented. 595 * 596 * @since Android 1.0 597 */ 598 @Deprecated destroy()599 public void destroy() { 600 throw new NoSuchMethodError("Thread.destroy()"); // TODO Externalize??? 601 } 602 603 /** 604 * Prints to the standard error stream a text representation of the current 605 * stack for this Thread. 606 * 607 * @see Throwable#printStackTrace() 608 * 609 * @since Android 1.0 610 */ dumpStack()611 public static void dumpStack() { 612 new Throwable("stack dump").printStackTrace(); 613 } 614 615 /** 616 * Copies an array with all Threads which are in the same ThreadGroup as the 617 * receiver - and subgroups - into the array <code>threads</code> passed as 618 * parameter. If the array passed as parameter is too small no exception is 619 * thrown - the extra elements are simply not copied. 620 * 621 * @param threads 622 * array into which the Threads will be copied 623 * @return How many Threads were copied over 624 * @throws SecurityException 625 * if the installed SecurityManager fails 626 * {@link SecurityManager#checkAccess(Thread)} 627 * @see java.lang.SecurityException 628 * @see java.lang.SecurityManager 629 * 630 * @since Android 1.0 631 */ enumerate(Thread[] threads)632 public static int enumerate(Thread[] threads) { 633 Thread thread = Thread.currentThread(); 634 thread.checkAccess(); 635 return thread.getThreadGroup().enumerate(threads); 636 } 637 638 /** 639 * <p> 640 * Returns the stack traces of all the currently live threads and puts them 641 * into the given map. 642 * </p> 643 * 644 * @return A Map of current Threads to StackTraceElement arrays. 645 * @throws SecurityException 646 * if the current SecurityManager fails the 647 * {@link SecurityManager#checkPermission(java.security.Permission)} 648 * call. 649 * 650 * @since Android 1.0 651 */ getAllStackTraces()652 public static Map<Thread, StackTraceElement[]> getAllStackTraces() { 653 SecurityManager securityManager = System.getSecurityManager(); 654 if (securityManager != null) { 655 securityManager.checkPermission(new RuntimePermission("getStackTrace")); 656 securityManager.checkPermission(new RuntimePermission("modifyThreadGroup")); 657 } 658 659 Map<Thread, StackTraceElement[]> map = new HashMap<Thread, StackTraceElement[]>(); 660 661 // Find out how many live threads we have. Allocate a bit more 662 // space than needed, in case new ones are just being created. 663 int count = ThreadGroup.mSystem.activeCount(); 664 Thread[] threads = new Thread[count + count / 2]; 665 666 // Enumerate the threads and collect the stacktraces. 667 count = ThreadGroup.mSystem.enumerate(threads); 668 for (int i = 0; i < count; i++) { 669 map.put(threads[i], threads[i].getStackTrace()); 670 } 671 672 return map; 673 } 674 675 /** 676 * Returns the context ClassLoader for this Thread. 677 * <p> 678 * If the conditions 679 * <ol> 680 * <li>there is a security manager 681 * <li>the caller's class loader is not null 682 * <li>the caller's class loader is not the same as the requested 683 * context class loader and not an ancestor thereof 684 * </ol> 685 * are satisfied, a security check for 686 * <code>RuntimePermission("getClassLoader")</code> is performed first. 687 * 688 * @return ClassLoader The context ClassLoader 689 * @see java.lang.ClassLoader 690 * @see #getContextClassLoader() 691 * 692 * @throws SecurityException 693 * if the aforementioned security check fails. 694 * 695 * @since Android 1.0 696 */ getContextClassLoader()697 public ClassLoader getContextClassLoader() { 698 // First, if the conditions 699 // 1) there is a security manager 700 // 2) the caller's class loader is not null 701 // 3) the caller's class loader is not the same as the context 702 // class loader and not an ancestor thereof 703 // are satisfied we should perform a security check. 704 SecurityManager sm = System.getSecurityManager(); 705 if (sm != null) { 706 ClassLoader calling = VMStack.getCallingClassLoader(); 707 708 if (calling != null && !calling.isAncestorOf(contextClassLoader)) { 709 sm.checkPermission(new RuntimePermission("getClassLoader")); 710 } 711 } 712 713 return contextClassLoader; 714 } 715 716 /** 717 * Returns the default exception handler that's executed when uncaught 718 * exception terminates a thread. 719 * 720 * @return an {@link UncaughtExceptionHandler} or <code>null</code> if 721 * none exists. 722 * 723 * @since Android 1.0 724 */ getDefaultUncaughtExceptionHandler()725 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() { 726 return defaultUncaughtHandler; 727 } 728 729 /** 730 * Returns the thread's identifier. The ID is a positive <code>long</code> 731 * generated on thread creation, is unique to the thread, and doesn't change 732 * during the lifetime of the thread; the ID may be reused after the thread 733 * has been terminated. 734 * 735 * @return the thread's ID. 736 * 737 * @since Android 1.0 738 */ getId()739 public long getId() { 740 return id; 741 } 742 743 /** 744 * Returns the name of the Thread. 745 * 746 * @return the Thread's name 747 * 748 * @since Android 1.0 749 */ getName()750 public final String getName() { 751 return name; 752 } 753 754 /** 755 * Returns the priority of the Thread. 756 * 757 * @return the Thread's priority 758 * @see Thread#setPriority 759 * 760 * @since Android 1.0 761 */ getPriority()762 public final int getPriority() { 763 return priority; 764 } 765 766 /** 767 * Returns the a stack trace representing the current execution state of 768 * this Thread. 769 * <p> 770 * The <code>RuntimePermission("getStackTrace")</code> is checked before 771 * returning a result. 772 * </p> 773 * 774 * @return an array of StackTraceElements. 775 * @throws SecurityException 776 * if the current SecurityManager fails the 777 * {@link SecurityManager#checkPermission(java.security.Permission)} 778 * call. 779 * 780 * @since Android 1.0 781 */ getStackTrace()782 public StackTraceElement[] getStackTrace() { 783 SecurityManager securityManager = System.getSecurityManager(); 784 if (securityManager != null) { 785 securityManager.checkPermission(new RuntimePermission("getStackTrace")); 786 } 787 788 StackTraceElement ste[] = VMStack.getThreadStackTrace(this); 789 return ste != null ? ste : new StackTraceElement[0]; 790 } 791 792 /** 793 * Returns the current state of the Thread. This method is useful for 794 * monitoring purposes. 795 * 796 * @return a {@link State} value. 797 * 798 * @since Android 1.0 799 */ getState()800 public State getState() { 801 // TODO This is ugly and should be implemented better. 802 VMThread vmt = this.vmThread; 803 804 // Make sure we have a valid reference to an object. If native code 805 // deletes the reference we won't run into a null reference later. 806 VMThread thread = vmThread; 807 if (thread != null) { 808 // If the Thread Object became invalid or was not yet started, 809 // getStatus() will return -1. 810 int state = thread.getStatus(); 811 if(state != -1) { 812 return VMThread.STATE_MAP[state]; 813 } 814 } 815 return hasBeenStarted ? Thread.State.TERMINATED : Thread.State.NEW; 816 } 817 818 /** 819 * Returns the ThreadGroup to which this Thread belongs. 820 * 821 * @return the Thread's ThreadGroup 822 * 823 * @since Android 1.0 824 */ getThreadGroup()825 public final ThreadGroup getThreadGroup() { 826 // TODO This should actually be done at native termination. 827 if (getState() == Thread.State.TERMINATED) { 828 return null; 829 } else { 830 return group; 831 } 832 } 833 834 /** 835 * Returns the thread's uncaught exception handler. If not explicitly set, 836 * then the ThreadGroup's handler is returned. If the thread is terminated, 837 * then <code>null</code> is returned. 838 * 839 * @return an {@link UncaughtExceptionHandler} instance or {@code null}. 840 * 841 * @since Android 1.0 842 */ getUncaughtExceptionHandler()843 public UncaughtExceptionHandler getUncaughtExceptionHandler() { 844 if (uncaughtHandler != null) 845 return uncaughtHandler; 846 else 847 return group; // ThreadGroup is instance of UEH 848 } 849 850 /** 851 * Posts an interrupt request to this {@code Thread}. Unless the caller is 852 * the {@link #currentThread()}, the method {@code checkAccess()} is called 853 * for the installed {@code SecurityManager}, if any. This may result in a 854 * {@code SecurityException} being thrown. The further behavior depends on 855 * the state of this {@code Thread}: 856 * <ul> 857 * <li> 858 * {@code Thread}s blocked in one of {@code Object}'s {@code wait()} methods 859 * or one of {@code Thread}'s {@code join()} or {@code sleep()} methods will 860 * be woken up, their interrupt status will be cleared, and they receive an 861 * {@link InterruptedException}. 862 * <li> 863 * {@code Thread}s blocked in an I/O operation of an 864 * {@link java.nio.channels.InterruptibleChannel} will have their interrupt 865 * status set and receive an 866 * {@link java.nio.channels.ClosedByInterruptException}. Also, the channel 867 * will be closed. 868 * <li> 869 * {@code Thread}s blocked in a {@link java.nio.channels.Selector} will have 870 * their interrupt status set and return immediately. They don't receive an 871 * exception in this case. 872 * <ul> 873 * 874 * @throws SecurityException 875 * if <code>checkAccess()</code> fails with a SecurityException 876 * @see java.lang.SecurityException 877 * @see java.lang.SecurityManager 878 * @see Thread#interrupted 879 * @see Thread#isInterrupted 880 * 881 * @since Android 1.0 882 */ interrupt()883 public void interrupt() { 884 checkAccess(); 885 886 if (interruptAction != null) { 887 interruptAction.run(); 888 } 889 890 VMThread vmt = this.vmThread; 891 if (vmt != null) { 892 vmt.interrupt(); 893 } 894 } 895 896 /** 897 * Returns a <code>boolean</code> indicating whether the current Thread ( 898 * <code>currentThread()</code>) has a pending interrupt request (<code> 899 * true</code>) or not (<code>false</code>). It also has the side-effect of 900 * clearing the flag. 901 * 902 * @return a <code>boolean</code> indicating the interrupt status 903 * @see Thread#currentThread 904 * @see Thread#interrupt 905 * @see Thread#isInterrupted 906 * 907 * @since Android 1.0 908 */ interrupted()909 public static boolean interrupted() { 910 return VMThread.interrupted(); 911 } 912 913 /** 914 * Returns <code>true</code> if the receiver has already been started and 915 * still runs code (hasn't died yet). Returns <code>false</code> either if 916 * the receiver hasn't been started yet or if it has already started and run 917 * to completion and died. 918 * 919 * @return a <code>boolean</code> indicating the lifeness of the Thread 920 * @see Thread#start 921 * 922 * @since Android 1.0 923 */ isAlive()924 public final boolean isAlive() { 925 return (vmThread != null); 926 } 927 928 /** 929 * Returns a <code>boolean</code> indicating whether the receiver is a 930 * daemon Thread (<code>true</code>) or not (<code>false</code>) A 931 * daemon Thread only runs as long as there are non-daemon Threads running. 932 * When the last non-daemon Thread ends, the whole program ends no matter if 933 * it had daemon Threads still running or not. 934 * 935 * @return a <code>boolean</code> indicating whether the Thread is a daemon 936 * @see Thread#setDaemon 937 * 938 * @since Android 1.0 939 */ isDaemon()940 public final boolean isDaemon() { 941 return daemon; 942 } 943 944 /** 945 * Returns a <code>boolean</code> indicating whether the receiver has a 946 * pending interrupt request (<code>true</code>) or not ( 947 * <code>false</code>) 948 * 949 * @return a <code>boolean</code> indicating the interrupt status 950 * @see Thread#interrupt 951 * @see Thread#interrupted 952 * 953 * @since Android 1.0 954 */ isInterrupted()955 public boolean isInterrupted() { 956 VMThread vmt = this.vmThread; 957 if (vmt != null) { 958 return vmt.isInterrupted(); 959 } 960 961 return false; 962 } 963 964 /** 965 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 966 * the receiver finishes its execution and dies. 967 * 968 * @throws InterruptedException if <code>interrupt()</code> was called for 969 * the receiver while it was in the <code>join()</code> call 970 * @see Object#notifyAll 971 * @see java.lang.ThreadDeath 972 * 973 * @since Android 1.0 974 */ join()975 public final void join() throws InterruptedException { 976 VMThread t = vmThread; 977 if (t == null) { 978 return; 979 } 980 981 synchronized (t) { 982 while (isAlive()) { 983 t.wait(); 984 } 985 } 986 } 987 988 /** 989 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 990 * the receiver finishes its execution and dies or the specified timeout 991 * expires, whatever happens first. 992 * 993 * @param millis The maximum time to wait (in milliseconds). 994 * @throws InterruptedException if <code>interrupt()</code> was called for 995 * the receiver while it was in the <code>join()</code> call 996 * @see Object#notifyAll 997 * @see java.lang.ThreadDeath 998 * 999 * @since Android 1.0 1000 */ join(long millis)1001 public final void join(long millis) throws InterruptedException { 1002 join(millis, 0); 1003 } 1004 1005 /** 1006 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 1007 * the receiver finishes its execution and dies or the specified timeout 1008 * expires, whatever happens first. 1009 * 1010 * @param millis The maximum time to wait (in milliseconds). 1011 * @param nanos Extra nanosecond precision 1012 * @throws InterruptedException if <code>interrupt()</code> was called for 1013 * the receiver while it was in the <code>join()</code> call 1014 * @see Object#notifyAll 1015 * @see java.lang.ThreadDeath 1016 * 1017 * @since Android 1.0 1018 */ join(long millis, int nanos)1019 public final void join(long millis, int nanos) throws InterruptedException { 1020 if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) { 1021 throw new IllegalArgumentException(); 1022 } 1023 1024 // avoid overflow: if total > 292,277 years, just wait forever 1025 boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI; 1026 boolean forever = (millis | nanos) == 0; 1027 if (forever | overflow) { 1028 join(); 1029 return; 1030 } 1031 1032 VMThread t = vmThread; 1033 if (t == null) { 1034 return; 1035 } 1036 1037 synchronized (t) { 1038 if (!isAlive()) { 1039 return; 1040 } 1041 1042 // guaranteed not to overflow 1043 long nanosToWait = millis * NANOS_PER_MILLI + nanos; 1044 1045 // wait until this thread completes or the timeout has elapsed 1046 long start = System.nanoTime(); 1047 while (true) { 1048 t.wait(millis, nanos); 1049 if (!isAlive()) { 1050 break; 1051 } 1052 long nanosElapsed = System.nanoTime() - start; 1053 long nanosRemaining = nanosToWait - nanosElapsed; 1054 if (nanosRemaining <= 0) { 1055 break; 1056 } 1057 millis = nanosRemaining / NANOS_PER_MILLI; 1058 nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI); 1059 } 1060 } 1061 } 1062 1063 /** 1064 * Resumes a suspended Thread. This is a no-op if the receiver was never 1065 * suspended, or suspended and already resumed. If the receiver is 1066 * suspended, however, makes it resume to the point where it was when it was 1067 * suspended. 1068 * 1069 * @throws SecurityException 1070 * if <code>checkAccess()</code> fails with a SecurityException 1071 * @see Thread#suspend() 1072 * @deprecated Used with deprecated method {@link Thread#suspend} 1073 * 1074 * @since Android 1.0 1075 */ 1076 @Deprecated resume()1077 public final void resume() { 1078 checkAccess(); 1079 1080 VMThread vmt = this.vmThread; 1081 if (vmt != null) { 1082 vmt.resume(); 1083 } 1084 } 1085 1086 /** 1087 * Calls the <code>run()</code> method of the Runnable object the receiver 1088 * holds. If no Runnable is set, does nothing. 1089 * 1090 * @see Thread#start 1091 * 1092 * @since Android 1.0 1093 */ run()1094 public void run() { 1095 if (target != null) { 1096 target.run(); 1097 } 1098 } 1099 1100 /** 1101 * Set the context ClassLoader for the receiver. 1102 * <p> 1103 * The <code>RuntimePermission("setContextClassLoader")</code> 1104 * is checked prior to setting the handler. 1105 * </p> 1106 * 1107 * @param cl The context ClassLoader 1108 * @throws SecurityException if the current SecurityManager fails the 1109 * checkPermission call. 1110 * @see java.lang.ClassLoader 1111 * @see #getContextClassLoader() 1112 * 1113 * @since Android 1.0 1114 */ setContextClassLoader(ClassLoader cl)1115 public void setContextClassLoader(ClassLoader cl) { 1116 SecurityManager securityManager = System.getSecurityManager(); 1117 if (securityManager != null) { 1118 securityManager.checkPermission(new RuntimePermission("setContextClassLoader")); 1119 } 1120 1121 contextClassLoader = cl; 1122 } 1123 1124 /** 1125 * Set if the receiver is a daemon Thread or not. This can only be done 1126 * before the Thread starts running. 1127 * 1128 * @param isDaemon 1129 * indicates whether the Thread should be daemon or not 1130 * @throws SecurityException 1131 * if <code>checkAccess()</code> fails with a SecurityException 1132 * @see Thread#isDaemon 1133 * 1134 * @since Android 1.0 1135 */ setDaemon(boolean isDaemon)1136 public final void setDaemon(boolean isDaemon) { 1137 checkAccess(); 1138 1139 if (hasBeenStarted) { 1140 throw new IllegalThreadStateException("Thread already started."); // TODO Externalize? 1141 } 1142 1143 if (vmThread == null) { 1144 daemon = isDaemon; 1145 } 1146 } 1147 1148 /** 1149 * <p> 1150 * Sets the default uncaught exception handler. This handler is invoked in 1151 * case any Thread dies due to an unhandled exception. 1152 * </p> 1153 * <p> 1154 * The <code>RuntimePermission("setDefaultUncaughtExceptionHandler")</code> 1155 * is checked prior to setting the handler. 1156 * </p> 1157 * 1158 * @param handler 1159 * The handler to set or <code>null</code>. 1160 * @throws SecurityException 1161 * if the current SecurityManager fails the checkPermission 1162 * call. 1163 * 1164 * @since Android 1.0 1165 */ setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler)1166 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 1167 SecurityManager securityManager = System.getSecurityManager(); 1168 if (securityManager != null) { 1169 securityManager.checkPermission(new RuntimePermission ("setDefaultUncaughtExceptionHandler")); 1170 } 1171 1172 Thread.defaultUncaughtHandler = handler; 1173 } 1174 1175 /** 1176 * Set the action to be executed when interruption, which is probably be 1177 * used to implement the interruptible channel. The action is null by 1178 * default. And if this method is invoked by passing in a non-null value, 1179 * this action's run() method will be invoked in <code>interrupt()</code>. 1180 * <p> 1181 * This is required internally by NIO, so even if it looks like it's 1182 * useless, don't delete it! 1183 * 1184 * @param action the action to be executed when interruption 1185 */ 1186 @SuppressWarnings("unused") setInterruptAction(Runnable action)1187 private void setInterruptAction(Runnable action) { 1188 this.interruptAction = action; 1189 } 1190 1191 /** 1192 * Sets the name of the Thread. 1193 * 1194 * @param threadName the new name for the Thread 1195 * @throws SecurityException if <code>checkAccess()</code> fails with a 1196 * SecurityException 1197 * @see Thread#getName 1198 * 1199 * @since Android 1.0 1200 */ setName(String threadName)1201 public final void setName(String threadName) { 1202 if (threadName == null) { 1203 throw new NullPointerException(); 1204 } 1205 1206 checkAccess(); 1207 1208 name = threadName; 1209 VMThread vmt = this.vmThread; 1210 if (vmt != null) { 1211 /* notify the VM that the thread name has changed */ 1212 vmt.nameChanged(threadName); 1213 } 1214 } 1215 1216 /** 1217 * Sets the priority of the Thread. Note that the final priority set may not 1218 * be the parameter that was passed - it will depend on the receiver's 1219 * ThreadGroup. The priority cannot be set to be higher than the receiver's 1220 * ThreadGroup's maxPriority(). 1221 * 1222 * @param priority 1223 * new priority for the Thread 1224 * @throws SecurityException 1225 * if <code>checkAccess()</code> fails with a SecurityException 1226 * @throws IllegalArgumentException 1227 * if the new priority is greater than Thread.MAX_PRIORITY or 1228 * less than Thread.MIN_PRIORITY 1229 * @see Thread#getPriority 1230 * 1231 * @since Android 1.0 1232 */ setPriority(int priority)1233 public final void setPriority(int priority) { 1234 checkAccess(); 1235 1236 if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { 1237 throw new IllegalArgumentException("Prioritiy out of range"); // TODO Externalize? 1238 } 1239 1240 if (priority > group.getMaxPriority()) { 1241 priority = group.getMaxPriority(); 1242 } 1243 1244 this.priority = priority; 1245 1246 VMThread vmt = this.vmThread; 1247 if (vmt != null) { 1248 vmt.setPriority(priority); 1249 } 1250 } 1251 1252 /** 1253 * <p> 1254 * Sets the uncaught exception handler. This handler is invoked in case this 1255 * Thread dies due to an unhandled exception. 1256 * </p> 1257 * 1258 * @param handler 1259 * The handler to set or <code>null</code>. 1260 * @throws SecurityException 1261 * if the current SecurityManager fails the checkAccess call. 1262 * 1263 * @since Android 1.0 1264 */ setUncaughtExceptionHandler(UncaughtExceptionHandler handler)1265 public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 1266 checkAccess(); 1267 1268 uncaughtHandler = handler; 1269 } 1270 1271 /** 1272 * Causes the thread which sent this message to sleep for the given interval 1273 * of time (given in milliseconds). The precision is not guaranteed - the 1274 * Thread may sleep more or less than requested. 1275 * 1276 * @param time 1277 * The time to sleep in milliseconds. 1278 * @throws InterruptedException 1279 * if <code>interrupt()</code> was called for this Thread while 1280 * it was sleeping 1281 * @see Thread#interrupt() 1282 * 1283 * @since Android 1.0 1284 */ sleep(long time)1285 public static void sleep(long time) throws InterruptedException { 1286 Thread.sleep(time, 0); 1287 } 1288 1289 /** 1290 * Causes the thread which sent this message to sleep for the given interval 1291 * of time (given in milliseconds and nanoseconds). The precision is not 1292 * guaranteed - the Thread may sleep more or less than requested. 1293 * 1294 * @param millis 1295 * The time to sleep in milliseconds. 1296 * @param nanos 1297 * Extra nanosecond precision 1298 * @throws InterruptedException 1299 * if <code>interrupt()</code> was called for this Thread while 1300 * it was sleeping 1301 * @see Thread#interrupt() 1302 * 1303 * @since Android 1.0 1304 */ sleep(long millis, int nanos)1305 public static void sleep(long millis, int nanos) throws InterruptedException { 1306 VMThread.sleep(millis, nanos); 1307 } 1308 1309 /** 1310 * Starts the new Thread of execution. The <code>run()</code> method of 1311 * the receiver will be called by the receiver Thread itself (and not the 1312 * Thread calling <code>start()</code>). 1313 * 1314 * @throws IllegalThreadStateException if the Thread has been started before 1315 * 1316 * @see Thread#run 1317 * 1318 * @since Android 1.0 1319 */ start()1320 public synchronized void start() { 1321 if (hasBeenStarted) { 1322 throw new IllegalThreadStateException("Thread already started."); // TODO Externalize? 1323 } 1324 1325 hasBeenStarted = true; 1326 1327 VMThread.create(this, stackSize); 1328 } 1329 1330 /** 1331 * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is 1332 * resumed if it was suspended and awakened if it was sleeping, so that it 1333 * can proceed to throw ThreadDeath. 1334 * 1335 * @throws SecurityException if <code>checkAccess()</code> fails with a 1336 * SecurityException 1337 * @deprecated because stopping a thread in this manner is unsafe and can 1338 * leave your application and the VM in an unpredictable state. 1339 * 1340 * @since Android 1.0 1341 */ 1342 @Deprecated stop()1343 public final void stop() { 1344 stop(new ThreadDeath()); 1345 } 1346 1347 /** 1348 * Requests the receiver Thread to stop and throw the 1349 * <code>throwable()</code>. The Thread is resumed if it was suspended 1350 * and awakened if it was sleeping, so that it can proceed to throw the 1351 * <code>throwable()</code>. 1352 * 1353 * @param throwable Throwable object to be thrown by the Thread 1354 * @throws SecurityException if <code>checkAccess()</code> fails with a 1355 * SecurityException 1356 * @throws NullPointerException if <code>throwable()</code> is 1357 * <code>null</code> 1358 * @deprecated because stopping a thread in this manner is unsafe and can 1359 * leave your application and the VM in an unpredictable state. 1360 * 1361 * @since Android 1.0 1362 */ 1363 @Deprecated stop(Throwable throwable)1364 public final synchronized void stop(Throwable throwable) { 1365 SecurityManager securityManager = System.getSecurityManager(); 1366 if (securityManager != null) { 1367 securityManager.checkAccess(this); 1368 if (Thread.currentThread() != this) { 1369 securityManager.checkPermission(new RuntimePermission("stopThread")); 1370 } 1371 } 1372 1373 if (throwable == null) { 1374 throw new NullPointerException(); 1375 } 1376 1377 VMThread vmt = this.vmThread; 1378 if (vmt != null) { 1379 vmt.stop(throwable); 1380 } 1381 } 1382 1383 /** 1384 * Suspends this Thread. This is a no-op if the receiver is suspended. If 1385 * the receiver <code>isAlive()</code> however, suspended it until <code> 1386 * resume()</code> is sent to it. Suspend requests are not queued, which 1387 * means that N requests are equivalent to just one - only one resume 1388 * request is needed in this case. 1389 * 1390 * @throws SecurityException 1391 * if <code>checkAccess()</code> fails with a SecurityException 1392 * @see Thread#resume() 1393 * @deprecated May cause deadlocks. 1394 * 1395 * @since Android 1.0 1396 */ 1397 @Deprecated suspend()1398 public final void suspend() { 1399 checkAccess(); 1400 1401 VMThread vmt = this.vmThread; 1402 if (vmt != null) { 1403 vmt.suspend(); 1404 } 1405 } 1406 1407 /** 1408 * Returns a string containing a concise, human-readable description of the 1409 * Thread. It includes the Thread's name, priority, and group name. 1410 * 1411 * @return a printable representation for the receiver. 1412 * 1413 * @since Android 1.0 1414 */ 1415 @Override toString()1416 public String toString() { 1417 return "Thread[" + name + "," + priority + "," + group.getName() + "]"; 1418 } 1419 1420 /** 1421 * Causes the calling Thread to yield execution time to another Thread that 1422 * is ready to run. The actual scheduling is implementation-dependent. 1423 * 1424 * @since Android 1.0 1425 */ yield()1426 public static void yield() { 1427 VMThread.yield(); 1428 } 1429 1430 /** 1431 * Indicates whether the current Thread has a monitor lock on the specified 1432 * object. 1433 * 1434 * @param object the object to test for the monitor lock 1435 * @return true if the current thread has a monitor lock on the specified 1436 * object; false otherwise 1437 * 1438 * @since Android 1.0 1439 */ holdsLock(Object object)1440 public static boolean holdsLock(Object object) { 1441 return currentThread().vmThread.holdsLock(object); 1442 } 1443 1444 /** 1445 * Implemented by objects that want to handle cases where a thread is being 1446 * terminated by an uncaught exception. Upon such termination, the handler 1447 * is notified of the terminating thread and causal exception. If there is 1448 * no explicit handler set then the thread's group is the default handler. 1449 * 1450 * @since Android 1.0 1451 */ 1452 public static interface UncaughtExceptionHandler { 1453 /** 1454 * The thread is being terminated by an uncaught exception. Further 1455 * exceptions thrown in this method are prevent the remainder of the 1456 * method from executing, but are otherwise ignored. 1457 * 1458 * @param thread the thread that has an uncaught exception 1459 * @param ex the exception that was thrown 1460 * 1461 * @since Android 1.0 1462 */ uncaughtException(Thread thread, Throwable ex)1463 void uncaughtException(Thread thread, Throwable ex); 1464 } 1465 1466 /** 1467 * Implementation of <code>unpark()</code>. See {@link LangAccessImpl}. 1468 */ unpark()1469 /*package*/ void unpark() { 1470 VMThread vmt = vmThread; 1471 1472 if (vmt == null) { 1473 /* 1474 * vmThread is null before the thread is start()ed. In 1475 * this case, we just go ahead and set the state to 1476 * PREEMPTIVELY_UNPARKED. Since this happens before the 1477 * thread is started, we don't have to worry about 1478 * synchronizing with it. 1479 */ 1480 parkState = ParkState.PREEMPTIVELY_UNPARKED; 1481 return; 1482 } 1483 1484 synchronized (vmt) { 1485 switch (parkState) { 1486 case ParkState.PREEMPTIVELY_UNPARKED: { 1487 /* 1488 * Nothing to do in this case: By definition, a 1489 * preemptively unparked thread is to remain in 1490 * the preemptively unparked state if it is told 1491 * to unpark. 1492 */ 1493 break; 1494 } 1495 case ParkState.UNPARKED: { 1496 parkState = ParkState.PREEMPTIVELY_UNPARKED; 1497 break; 1498 } 1499 default /*parked*/: { 1500 parkState = ParkState.UNPARKED; 1501 vmt.notifyAll(); 1502 break; 1503 } 1504 } 1505 } 1506 } 1507 1508 /** 1509 * Implementation of <code>parkFor()</code>. See {@link LangAccessImpl}. 1510 * This method must only be called when <code>this</code> is the current 1511 * thread. 1512 * 1513 * @param nanos number of nanoseconds to park for 1514 */ parkFor(long nanos)1515 /*package*/ void parkFor(long nanos) { 1516 VMThread vmt = vmThread; 1517 1518 if (vmt == null) { 1519 // Running threads should always have an associated vmThread. 1520 throw new AssertionError(); 1521 } 1522 1523 synchronized (vmt) { 1524 switch (parkState) { 1525 case ParkState.PREEMPTIVELY_UNPARKED: { 1526 parkState = ParkState.UNPARKED; 1527 break; 1528 } 1529 case ParkState.UNPARKED: { 1530 long millis = nanos / NANOS_PER_MILLI; 1531 nanos %= NANOS_PER_MILLI; 1532 1533 parkState = ParkState.PARKED; 1534 try { 1535 vmt.wait(millis, (int) nanos); 1536 } catch (InterruptedException ex) { 1537 interrupt(); 1538 } finally { 1539 /* 1540 * Note: If parkState manages to become 1541 * PREEMPTIVELY_UNPARKED before hitting this 1542 * code, it should left in that state. 1543 */ 1544 if (parkState == ParkState.PARKED) { 1545 parkState = ParkState.UNPARKED; 1546 } 1547 } 1548 break; 1549 } 1550 default /*parked*/: { 1551 throw new AssertionError( 1552 "shouldn't happen: attempt to repark"); 1553 } 1554 } 1555 } 1556 } 1557 1558 /** 1559 * Implementation of <code>parkUntil()</code>. See {@link LangAccessImpl}. 1560 * This method must only be called when <code>this</code> is the current 1561 * thread. 1562 * 1563 * @param time absolute milliseconds since the epoch to park until 1564 */ parkUntil(long time)1565 /*package*/ void parkUntil(long time) { 1566 VMThread vmt = vmThread; 1567 1568 if (vmt == null) { 1569 // Running threads should always have an associated vmThread. 1570 throw new AssertionError(); 1571 } 1572 1573 synchronized (vmt) { 1574 /* 1575 * Note: This conflates the two time bases of "wall clock" 1576 * time and "monotonic uptime" time. However, given that 1577 * the underlying system can only wait on monotonic time, 1578 * it is unclear if there is any way to avoid the 1579 * conflation. The downside here is that if, having 1580 * calculated the delay, the wall clock gets moved ahead, 1581 * this method may not return until well after the wall 1582 * clock has reached the originally designated time. The 1583 * reverse problem (the wall clock being turned back) 1584 * isn't a big deal, since this method is allowed to 1585 * spuriously return for any reason, and this situation 1586 * can safely be construed as just such a spurious return. 1587 */ 1588 long delayMillis = time - System.currentTimeMillis(); 1589 1590 if (delayMillis <= 0) { 1591 parkState = ParkState.UNPARKED; 1592 } else { 1593 parkFor(delayMillis * NANOS_PER_MILLI); 1594 } 1595 } 1596 } 1597 } 1598