1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent; 37 38 import static java.lang.ref.Reference.reachabilityFence; 39 import dalvik.annotation.optimization.ReachabilitySensitive; 40 import java.lang.ref.Cleaner.Cleanable; 41 import java.security.AccessControlContext; 42 import java.security.AccessControlException; 43 import java.security.AccessController; 44 import java.security.PrivilegedAction; 45 import java.security.PrivilegedActionException; 46 import java.security.PrivilegedExceptionAction; 47 import java.util.Collection; 48 import java.util.List; 49 import java.util.concurrent.atomic.AtomicInteger; 50 import jdk.internal.ref.CleanerFactory; 51 import sun.security.util.SecurityConstants; 52 53 // BEGIN android-note 54 // removed security manager docs 55 // END android-note 56 57 /** 58 * Factory and utility methods for {@link Executor}, {@link 59 * ExecutorService}, {@link ScheduledExecutorService}, {@link 60 * ThreadFactory}, and {@link Callable} classes defined in this 61 * package. This class supports the following kinds of methods: 62 * 63 * <ul> 64 * <li>Methods that create and return an {@link ExecutorService} 65 * set up with commonly useful configuration settings. 66 * <li>Methods that create and return a {@link ScheduledExecutorService} 67 * set up with commonly useful configuration settings. 68 * <li>Methods that create and return a "wrapped" ExecutorService, that 69 * disables reconfiguration by making implementation-specific methods 70 * inaccessible. 71 * <li>Methods that create and return a {@link ThreadFactory} 72 * that sets newly created threads to a known state. 73 * <li>Methods that create and return a {@link Callable} 74 * out of other closure-like forms, so they can be used 75 * in execution methods requiring {@code Callable}. 76 * </ul> 77 * 78 * @since 1.5 79 * @author Doug Lea 80 */ 81 public class Executors { 82 83 /** 84 * Creates a thread pool that reuses a fixed number of threads 85 * operating off a shared unbounded queue. At any point, at most 86 * {@code nThreads} threads will be active processing tasks. 87 * If additional tasks are submitted when all threads are active, 88 * they will wait in the queue until a thread is available. 89 * If any thread terminates due to a failure during execution 90 * prior to shutdown, a new one will take its place if needed to 91 * execute subsequent tasks. The threads in the pool will exist 92 * until it is explicitly {@link ExecutorService#shutdown shutdown}. 93 * 94 * @param nThreads the number of threads in the pool 95 * @return the newly created thread pool 96 * @throws IllegalArgumentException if {@code nThreads <= 0} 97 */ newFixedThreadPool(int nThreads)98 public static ExecutorService newFixedThreadPool(int nThreads) { 99 return new ThreadPoolExecutor(nThreads, nThreads, 100 0L, TimeUnit.MILLISECONDS, 101 new LinkedBlockingQueue<Runnable>()); 102 } 103 104 /** 105 * Creates a thread pool that maintains enough threads to support 106 * the given parallelism level, and may use multiple queues to 107 * reduce contention. The parallelism level corresponds to the 108 * maximum number of threads actively engaged in, or available to 109 * engage in, task processing. The actual number of threads may 110 * grow and shrink dynamically. A work-stealing pool makes no 111 * guarantees about the order in which submitted tasks are 112 * executed. 113 * 114 * @param parallelism the targeted parallelism level 115 * @return the newly created thread pool 116 * @throws IllegalArgumentException if {@code parallelism <= 0} 117 * @since 1.8 118 */ newWorkStealingPool(int parallelism)119 public static ExecutorService newWorkStealingPool(int parallelism) { 120 return new ForkJoinPool 121 (parallelism, 122 ForkJoinPool.defaultForkJoinWorkerThreadFactory, 123 null, true); 124 } 125 126 /** 127 * Creates a work-stealing thread pool using the number of 128 * {@linkplain Runtime#availableProcessors available processors} 129 * as its target parallelism level. 130 * 131 * @return the newly created thread pool 132 * @see #newWorkStealingPool(int) 133 * @since 1.8 134 */ newWorkStealingPool()135 public static ExecutorService newWorkStealingPool() { 136 return new ForkJoinPool 137 (Runtime.getRuntime().availableProcessors(), 138 ForkJoinPool.defaultForkJoinWorkerThreadFactory, 139 null, true); 140 } 141 142 /** 143 * Creates a thread pool that reuses a fixed number of threads 144 * operating off a shared unbounded queue, using the provided 145 * ThreadFactory to create new threads when needed. At any point, 146 * at most {@code nThreads} threads will be active processing 147 * tasks. If additional tasks are submitted when all threads are 148 * active, they will wait in the queue until a thread is 149 * available. If any thread terminates due to a failure during 150 * execution prior to shutdown, a new one will take its place if 151 * needed to execute subsequent tasks. The threads in the pool will 152 * exist until it is explicitly {@link ExecutorService#shutdown 153 * shutdown}. 154 * 155 * @param nThreads the number of threads in the pool 156 * @param threadFactory the factory to use when creating new threads 157 * @return the newly created thread pool 158 * @throws NullPointerException if threadFactory is null 159 * @throws IllegalArgumentException if {@code nThreads <= 0} 160 */ newFixedThreadPool(int nThreads, ThreadFactory threadFactory)161 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { 162 return new ThreadPoolExecutor(nThreads, nThreads, 163 0L, TimeUnit.MILLISECONDS, 164 new LinkedBlockingQueue<Runnable>(), 165 threadFactory); 166 } 167 168 /** 169 * Creates an Executor that uses a single worker thread operating 170 * off an unbounded queue. (Note however that if this single 171 * thread terminates due to a failure during execution prior to 172 * shutdown, a new one will take its place if needed to execute 173 * subsequent tasks.) Tasks are guaranteed to execute 174 * sequentially, and no more than one task will be active at any 175 * given time. Unlike the otherwise equivalent 176 * {@code newFixedThreadPool(1)} the returned executor is 177 * guaranteed not to be reconfigurable to use additional threads. 178 * 179 * @return the newly created single-threaded Executor 180 */ newSingleThreadExecutor()181 public static ExecutorService newSingleThreadExecutor() { 182 return newSingleThreadExecutor(defaultThreadFactory()); 183 } 184 185 /** 186 * Creates an Executor that uses a single worker thread operating 187 * off an unbounded queue, and uses the provided ThreadFactory to 188 * create a new thread when needed. Unlike the otherwise 189 * equivalent {@code newFixedThreadPool(1, threadFactory)} the 190 * returned executor is guaranteed not to be reconfigurable to use 191 * additional threads. 192 * 193 * @param threadFactory the factory to use when creating new threads 194 * @return the newly created single-threaded Executor 195 * @throws NullPointerException if threadFactory is null 196 */ newSingleThreadExecutor(ThreadFactory threadFactory)197 public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { 198 return new AutoShutdownDelegatedExecutorService 199 (new ThreadPoolExecutor(1, 1, 200 0L, TimeUnit.MILLISECONDS, 201 new LinkedBlockingQueue<Runnable>(), 202 threadFactory)); 203 } 204 205 /** 206 * Creates a thread pool that creates new threads as needed, but 207 * will reuse previously constructed threads when they are 208 * available. These pools will typically improve the performance 209 * of programs that execute many short-lived asynchronous tasks. 210 * Calls to {@code execute} will reuse previously constructed 211 * threads if available. If no existing thread is available, a new 212 * thread will be created and added to the pool. Threads that have 213 * not been used for sixty seconds are terminated and removed from 214 * the cache. Thus, a pool that remains idle for long enough will 215 * not consume any resources. Note that pools with similar 216 * properties but different details (for example, timeout parameters) 217 * may be created using {@link ThreadPoolExecutor} constructors. 218 * 219 * @return the newly created thread pool 220 */ newCachedThreadPool()221 public static ExecutorService newCachedThreadPool() { 222 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 223 60L, TimeUnit.SECONDS, 224 new SynchronousQueue<Runnable>()); 225 } 226 227 /** 228 * Creates a thread pool that creates new threads as needed, but 229 * will reuse previously constructed threads when they are 230 * available, and uses the provided 231 * ThreadFactory to create new threads when needed. 232 * 233 * @param threadFactory the factory to use when creating new threads 234 * @return the newly created thread pool 235 * @throws NullPointerException if threadFactory is null 236 */ newCachedThreadPool(ThreadFactory threadFactory)237 public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { 238 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 239 60L, TimeUnit.SECONDS, 240 new SynchronousQueue<Runnable>(), 241 threadFactory); 242 } 243 244 /** 245 * Creates an Executor that starts a new Thread for each task. 246 * The number of threads created by the Executor is unbounded. 247 * 248 * <p> Invoking {@link Future#cancel(boolean) cancel(true)} on a {@link 249 * Future Future} representing the pending result of a task submitted to 250 * the Executor will {@link Thread#interrupt() interrupt} the thread 251 * executing the task. 252 * 253 * @param threadFactory the factory to use when creating new threads 254 * @return a new executor that creates a new Thread for each task 255 * @throws NullPointerException if threadFactory is null 256 * @since 21 257 */ 258 // Android-removed: ThreadPerTaskExecutor not available. 259 // TODO(b/346542404): Re-enable this API when VirtualThread is available 260 // public static ExecutorService newThreadPerTaskExecutor(ThreadFactory threadFactory) { 261 // return ThreadPerTaskExecutor.create(threadFactory); 262 // } 263 264 /** 265 * Creates an Executor that starts a new virtual Thread for each task. 266 * The number of threads created by the Executor is unbounded. 267 * 268 * <p> This method is equivalent to invoking 269 * {@link #newThreadPerTaskExecutor(ThreadFactory)} with a thread factory 270 * that creates virtual threads. 271 * 272 * @return a new executor that creates a new virtual Thread for each task 273 * @since 21 274 */ 275 // Android-removed: Virtual threads not available. 276 // TODO(b/346542404): Re-enable this API when VirtualThread is available 277 // public static ExecutorService newVirtualThreadPerTaskExecutor() { 278 // ThreadFactory factory = Thread.ofVirtual().factory(); 279 // return newThreadPerTaskExecutor(factory); 280 // } 281 282 /** 283 * Creates a single-threaded executor that can schedule commands 284 * to run after a given delay, or to execute periodically. 285 * (Note however that if this single 286 * thread terminates due to a failure during execution prior to 287 * shutdown, a new one will take its place if needed to execute 288 * subsequent tasks.) Tasks are guaranteed to execute 289 * sequentially, and no more than one task will be active at any 290 * given time. Unlike the otherwise equivalent 291 * {@code newScheduledThreadPool(1)} the returned executor is 292 * guaranteed not to be reconfigurable to use additional threads. 293 * 294 * @return the newly created scheduled executor 295 */ newSingleThreadScheduledExecutor()296 public static ScheduledExecutorService newSingleThreadScheduledExecutor() { 297 return new DelegatedScheduledExecutorService 298 (new ScheduledThreadPoolExecutor(1)); 299 } 300 301 /** 302 * Creates a single-threaded executor that can schedule commands 303 * to run after a given delay, or to execute periodically. (Note 304 * however that if this single thread terminates due to a failure 305 * during execution prior to shutdown, a new one will take its 306 * place if needed to execute subsequent tasks.) Tasks are 307 * guaranteed to execute sequentially, and no more than one task 308 * will be active at any given time. Unlike the otherwise 309 * equivalent {@code newScheduledThreadPool(1, threadFactory)} 310 * the returned executor is guaranteed not to be reconfigurable to 311 * use additional threads. 312 * 313 * @param threadFactory the factory to use when creating new threads 314 * @return the newly created scheduled executor 315 * @throws NullPointerException if threadFactory is null 316 */ newSingleThreadScheduledExecutor(ThreadFactory threadFactory)317 public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) { 318 return new DelegatedScheduledExecutorService 319 (new ScheduledThreadPoolExecutor(1, threadFactory)); 320 } 321 322 /** 323 * Creates a thread pool that can schedule commands to run after a 324 * given delay, or to execute periodically. 325 * @param corePoolSize the number of threads to keep in the pool, 326 * even if they are idle 327 * @return the newly created scheduled thread pool 328 * @throws IllegalArgumentException if {@code corePoolSize < 0} 329 */ newScheduledThreadPool(int corePoolSize)330 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { 331 return new ScheduledThreadPoolExecutor(corePoolSize); 332 } 333 334 /** 335 * Creates a thread pool that can schedule commands to run after a 336 * given delay, or to execute periodically. 337 * @param corePoolSize the number of threads to keep in the pool, 338 * even if they are idle 339 * @param threadFactory the factory to use when the executor 340 * creates a new thread 341 * @return the newly created scheduled thread pool 342 * @throws IllegalArgumentException if {@code corePoolSize < 0} 343 * @throws NullPointerException if threadFactory is null 344 */ newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory)345 public static ScheduledExecutorService newScheduledThreadPool( 346 int corePoolSize, ThreadFactory threadFactory) { 347 return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); 348 } 349 350 /** 351 * Returns an object that delegates all defined {@link 352 * ExecutorService} methods to the given executor, but not any 353 * other methods that might otherwise be accessible using 354 * casts. This provides a way to safely "freeze" configuration and 355 * disallow tuning of a given concrete implementation. 356 * @param executor the underlying implementation 357 * @return an {@code ExecutorService} instance 358 * @throws NullPointerException if executor null 359 */ unconfigurableExecutorService(ExecutorService executor)360 public static ExecutorService unconfigurableExecutorService(ExecutorService executor) { 361 if (executor == null) 362 throw new NullPointerException(); 363 return new DelegatedExecutorService(executor); 364 } 365 366 /** 367 * Returns an object that delegates all defined {@link 368 * ScheduledExecutorService} methods to the given executor, but 369 * not any other methods that might otherwise be accessible using 370 * casts. This provides a way to safely "freeze" configuration and 371 * disallow tuning of a given concrete implementation. 372 * @param executor the underlying implementation 373 * @return a {@code ScheduledExecutorService} instance 374 * @throws NullPointerException if executor null 375 */ unconfigurableScheduledExecutorService(ScheduledExecutorService executor)376 public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) { 377 if (executor == null) 378 throw new NullPointerException(); 379 return new DelegatedScheduledExecutorService(executor); 380 } 381 382 // Android-changed: Removed references to SecurityManager from javadoc. 383 /** 384 * Returns a default thread factory used to create new threads. 385 * This factory creates all new threads used by an Executor in the 386 * same {@link ThreadGroup}. Each new 387 * thread is created as a non-daemon thread with priority set to 388 * the smaller of {@code Thread.NORM_PRIORITY} and the maximum 389 * priority permitted in the thread group. New threads have names 390 * accessible via {@link Thread#getName} of 391 * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence 392 * number of this factory, and <em>M</em> is the sequence number 393 * of the thread created by this factory. 394 * @return a thread factory 395 */ defaultThreadFactory()396 public static ThreadFactory defaultThreadFactory() { 397 return new DefaultThreadFactory(); 398 } 399 400 // Android-changed: Dropped documentation for legacy security code. 401 /** 402 * Legacy security code; do not use. 403 * 404 * @deprecated This method is only useful in conjunction with 405 * {@linkplain SecurityManager the Security Manager}, which is 406 * deprecated and subject to removal in a future release. 407 * Consequently, this method is also deprecated and subject to 408 * removal. There is no replacement for the Security Manager or this 409 * method. 410 */ 411 @Deprecated(since="17", forRemoval=true) privilegedThreadFactory()412 public static ThreadFactory privilegedThreadFactory() { 413 return new PrivilegedThreadFactory(); 414 } 415 416 /** 417 * Returns a {@link Callable} object that, when 418 * called, runs the given task and returns the given result. This 419 * can be useful when applying methods requiring a 420 * {@code Callable} to an otherwise resultless action. 421 * @param task the task to run 422 * @param result the result to return 423 * @param <T> the type of the result 424 * @return a callable object 425 * @throws NullPointerException if task null 426 */ callable(Runnable task, T result)427 public static <T> Callable<T> callable(Runnable task, T result) { 428 if (task == null) 429 throw new NullPointerException(); 430 return new RunnableAdapter<T>(task, result); 431 } 432 433 /** 434 * Returns a {@link Callable} object that, when 435 * called, runs the given task and returns {@code null}. 436 * @param task the task to run 437 * @return a callable object 438 * @throws NullPointerException if task null 439 */ callable(Runnable task)440 public static Callable<Object> callable(Runnable task) { 441 if (task == null) 442 throw new NullPointerException(); 443 return new RunnableAdapter<Object>(task, null); 444 } 445 446 /** 447 * Returns a {@link Callable} object that, when 448 * called, runs the given privileged action and returns its result. 449 * @param action the privileged action to run 450 * @return a callable object 451 * @throws NullPointerException if action null 452 */ callable(final PrivilegedAction<?> action)453 public static Callable<Object> callable(final PrivilegedAction<?> action) { 454 if (action == null) 455 throw new NullPointerException(); 456 return new Callable<Object>() { 457 public Object call() { return action.run(); }}; 458 } 459 460 /** 461 * Returns a {@link Callable} object that, when 462 * called, runs the given privileged exception action and returns 463 * its result. 464 * @param action the privileged exception action to run 465 * @return a callable object 466 * @throws NullPointerException if action null 467 */ 468 public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) { 469 if (action == null) 470 throw new NullPointerException(); 471 return new Callable<Object>() { 472 public Object call() throws Exception { return action.run(); }}; 473 } 474 475 // Android-changed: Dropped documentation for legacy security code. 476 /** 477 * Legacy security code; do not use. 478 * 479 * @deprecated This method is only useful in conjunction with 480 * {@linkplain SecurityManager the Security Manager}, which is 481 * deprecated and subject to removal in a future release. 482 * Consequently, this method is also deprecated and subject to 483 * removal. There is no replacement for the Security Manager or this 484 * method. 485 */ 486 @Deprecated(since="17", forRemoval=true) 487 public static <T> Callable<T> privilegedCallable(Callable<T> callable) { 488 if (callable == null) 489 throw new NullPointerException(); 490 return new PrivilegedCallable<T>(callable); 491 } 492 493 // Android-changed: Dropped documentation for legacy security code. 494 /** 495 * Legacy security code; do not use. 496 * 497 * @deprecated This method is only useful in conjunction with 498 * {@linkplain SecurityManager the Security Manager}, which is 499 * deprecated and subject to removal in a future release. 500 * Consequently, this method is also deprecated and subject to 501 * removal. There is no replacement for the Security Manager or this 502 * method. 503 */ 504 @Deprecated(since="17", forRemoval=true) 505 public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) { 506 if (callable == null) 507 throw new NullPointerException(); 508 return new PrivilegedCallableUsingCurrentClassLoader<T>(callable); 509 } 510 511 // Non-public classes supporting the public methods 512 513 /** 514 * A callable that runs given task and returns given result. 515 */ 516 private static final class RunnableAdapter<T> implements Callable<T> { 517 private final Runnable task; 518 private final T result; 519 RunnableAdapter(Runnable task, T result) { 520 this.task = task; 521 this.result = result; 522 } 523 public T call() { 524 task.run(); 525 return result; 526 } 527 public String toString() { 528 return super.toString() + "[Wrapped task = " + task + "]"; 529 } 530 } 531 532 /** 533 * A callable that runs under established access control settings. 534 */ 535 private static final class PrivilegedCallable<T> implements Callable<T> { 536 final Callable<T> task; 537 @SuppressWarnings("removal") 538 final AccessControlContext acc; 539 540 @SuppressWarnings("removal") 541 PrivilegedCallable(Callable<T> task) { 542 this.task = task; 543 this.acc = AccessController.getContext(); 544 } 545 546 @SuppressWarnings("removal") 547 public T call() throws Exception { 548 try { 549 return AccessController.doPrivileged( 550 new PrivilegedExceptionAction<T>() { 551 public T run() throws Exception { 552 return task.call(); 553 } 554 }, acc); 555 } catch (PrivilegedActionException e) { 556 throw e.getException(); 557 } 558 } 559 560 public String toString() { 561 return super.toString() + "[Wrapped task = " + task + "]"; 562 } 563 } 564 565 /** 566 * A callable that runs under established access control settings and 567 * current ClassLoader. 568 */ 569 private static final class PrivilegedCallableUsingCurrentClassLoader<T> 570 implements Callable<T> { 571 final Callable<T> task; 572 @SuppressWarnings("removal") 573 final AccessControlContext acc; 574 final ClassLoader ccl; 575 576 @SuppressWarnings("removal") 577 PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) { 578 // Android-removed: System.getSecurityManager always returns null. 579 /* 580 SecurityManager sm = System.getSecurityManager(); 581 if (sm != null) { 582 // Calls to getContextClassLoader from this class 583 // never trigger a security check, but we check 584 // whether our callers have this permission anyways. 585 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 586 587 // Whether setContextClassLoader turns out to be necessary 588 // or not, we fail fast if permission is not available. 589 sm.checkPermission(new RuntimePermission("setContextClassLoader")); 590 } 591 */ 592 this.task = task; 593 this.acc = AccessController.getContext(); 594 this.ccl = Thread.currentThread().getContextClassLoader(); 595 } 596 597 @SuppressWarnings("removal") 598 public T call() throws Exception { 599 try { 600 return AccessController.doPrivileged( 601 new PrivilegedExceptionAction<T>() { 602 public T run() throws Exception { 603 Thread t = Thread.currentThread(); 604 ClassLoader cl = t.getContextClassLoader(); 605 if (ccl == cl) { 606 return task.call(); 607 } else { 608 t.setContextClassLoader(ccl); 609 try { 610 return task.call(); 611 } finally { 612 t.setContextClassLoader(cl); 613 } 614 } 615 } 616 }, acc); 617 } catch (PrivilegedActionException e) { 618 throw e.getException(); 619 } 620 } 621 622 public String toString() { 623 return super.toString() + "[Wrapped task = " + task + "]"; 624 } 625 } 626 627 /** 628 * The default thread factory. 629 */ 630 private static class DefaultThreadFactory implements ThreadFactory { 631 private static final AtomicInteger poolNumber = new AtomicInteger(1); 632 private final ThreadGroup group; 633 private final AtomicInteger threadNumber = new AtomicInteger(1); 634 private final String namePrefix; 635 636 DefaultThreadFactory() { 637 @SuppressWarnings("removal") 638 SecurityManager s = System.getSecurityManager(); 639 group = (s != null) ? s.getThreadGroup() : 640 Thread.currentThread().getThreadGroup(); 641 namePrefix = "pool-" + 642 poolNumber.getAndIncrement() + 643 "-thread-"; 644 } 645 646 public Thread newThread(Runnable r) { 647 Thread t = new Thread(group, r, 648 namePrefix + threadNumber.getAndIncrement(), 649 0); 650 if (t.isDaemon()) 651 t.setDaemon(false); 652 if (t.getPriority() != Thread.NORM_PRIORITY) 653 t.setPriority(Thread.NORM_PRIORITY); 654 return t; 655 } 656 } 657 658 /** 659 * Thread factory capturing access control context and class loader. 660 */ 661 private static class PrivilegedThreadFactory extends DefaultThreadFactory { 662 @SuppressWarnings("removal") 663 final AccessControlContext acc; 664 final ClassLoader ccl; 665 666 @SuppressWarnings("removal") 667 PrivilegedThreadFactory() { 668 super(); 669 // Android-removed: System.getSecurityManager always returns null. 670 /* 671 SecurityManager sm = System.getSecurityManager(); 672 if (sm != null) { 673 // Calls to getContextClassLoader from this class 674 // never trigger a security check, but we check 675 // whether our callers have this permission anyways. 676 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 677 678 // Fail fast 679 sm.checkPermission(new RuntimePermission("setContextClassLoader")); 680 } 681 */ 682 this.acc = AccessController.getContext(); 683 this.ccl = Thread.currentThread().getContextClassLoader(); 684 } 685 686 public Thread newThread(final Runnable r) { 687 return super.newThread(new Runnable() { 688 @SuppressWarnings("removal") 689 public void run() { 690 AccessController.doPrivileged(new PrivilegedAction<>() { 691 public Void run() { 692 Thread.currentThread().setContextClassLoader(ccl); 693 r.run(); 694 return null; 695 } 696 }, acc); 697 } 698 }); 699 } 700 } 701 702 /** 703 * A wrapper class that exposes only the ExecutorService methods 704 * of an ExecutorService implementation. 705 */ 706 private static class DelegatedExecutorService 707 implements ExecutorService { 708 // Android-added: @ReachabilitySensitive 709 // Needed for FinalizableDelegatedExecutorService below. 710 @ReachabilitySensitive 711 private final ExecutorService e; 712 DelegatedExecutorService(ExecutorService executor) { e = executor; } 713 public void execute(Runnable command) { 714 try { 715 e.execute(command); 716 } finally { reachabilityFence(this); } 717 } 718 public void shutdown() { 719 try { 720 e.shutdown(); 721 } finally { reachabilityFence(this); } 722 } 723 public List<Runnable> shutdownNow() { 724 try { 725 return e.shutdownNow(); 726 } finally { reachabilityFence(this); } 727 } 728 public boolean isShutdown() { 729 try { 730 return e.isShutdown(); 731 } finally { reachabilityFence(this); } 732 } 733 public boolean isTerminated() { 734 try { 735 return e.isTerminated(); 736 } finally { reachabilityFence(this); } 737 } 738 public boolean awaitTermination(long timeout, TimeUnit unit) 739 throws InterruptedException { 740 try { 741 return e.awaitTermination(timeout, unit); 742 } finally { reachabilityFence(this); } 743 } 744 public Future<?> submit(Runnable task) { 745 try { 746 return e.submit(task); 747 } finally { reachabilityFence(this); } 748 } 749 public <T> Future<T> submit(Callable<T> task) { 750 try { 751 return e.submit(task); 752 } finally { reachabilityFence(this); } 753 } 754 public <T> Future<T> submit(Runnable task, T result) { 755 try { 756 return e.submit(task, result); 757 } finally { reachabilityFence(this); } 758 } 759 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 760 throws InterruptedException { 761 try { 762 return e.invokeAll(tasks); 763 } finally { reachabilityFence(this); } 764 } 765 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, 766 long timeout, TimeUnit unit) 767 throws InterruptedException { 768 try { 769 return e.invokeAll(tasks, timeout, unit); 770 } finally { reachabilityFence(this); } 771 } 772 public <T> T invokeAny(Collection<? extends Callable<T>> tasks) 773 throws InterruptedException, ExecutionException { 774 try { 775 return e.invokeAny(tasks); 776 } finally { reachabilityFence(this); } 777 } 778 public <T> T invokeAny(Collection<? extends Callable<T>> tasks, 779 long timeout, TimeUnit unit) 780 throws InterruptedException, ExecutionException, TimeoutException { 781 try { 782 return e.invokeAny(tasks, timeout, unit); 783 } finally { reachabilityFence(this); } 784 } 785 } 786 787 /** 788 * A DelegatedExecutorService that uses a Cleaner to shut down the underlying 789 * ExecutorService when the wrapper becomes phantom reachable. 790 */ 791 private static class AutoShutdownDelegatedExecutorService 792 extends DelegatedExecutorService { 793 private final Cleanable cleanable; 794 AutoShutdownDelegatedExecutorService(ExecutorService executor) { 795 super(executor); 796 Runnable action = () -> { 797 if (!executor.isShutdown()) { 798 PrivilegedAction<Void> pa = () -> { executor.shutdown(); return null; }; 799 @SuppressWarnings("removal") 800 var ignore = AccessController.doPrivileged(pa); 801 } 802 }; 803 cleanable = CleanerFactory.cleaner().register(this, action); 804 } 805 @Override 806 public void shutdown() { 807 super.shutdown(); 808 cleanable.clean(); // unregisters the cleanable 809 } 810 } 811 812 /** 813 * A wrapper class that exposes only the ScheduledExecutorService 814 * methods of a ScheduledExecutorService implementation. 815 */ 816 private static class DelegatedScheduledExecutorService 817 extends DelegatedExecutorService 818 implements ScheduledExecutorService { 819 private final ScheduledExecutorService e; 820 DelegatedScheduledExecutorService(ScheduledExecutorService executor) { 821 super(executor); 822 e = executor; 823 } 824 public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { 825 return e.schedule(command, delay, unit); 826 } 827 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { 828 return e.schedule(callable, delay, unit); 829 } 830 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { 831 return e.scheduleAtFixedRate(command, initialDelay, period, unit); 832 } 833 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { 834 return e.scheduleWithFixedDelay(command, initialDelay, delay, unit); 835 } 836 } 837 838 /** Cannot instantiate. */ 839 private Executors() {} 840 } 841