001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019 020import com.google.common.annotations.Beta; 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.annotations.VisibleForTesting; 024import com.google.common.base.Supplier; 025import com.google.common.base.Throwables; 026import com.google.common.collect.Lists; 027import com.google.common.collect.Queues; 028import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture; 029import com.google.errorprone.annotations.CanIgnoreReturnValue; 030import java.lang.reflect.InvocationTargetException; 031import java.util.Collection; 032import java.util.Collections; 033import java.util.Iterator; 034import java.util.List; 035import java.util.concurrent.BlockingQueue; 036import java.util.concurrent.Callable; 037import java.util.concurrent.Delayed; 038import java.util.concurrent.ExecutionException; 039import java.util.concurrent.Executor; 040import java.util.concurrent.ExecutorService; 041import java.util.concurrent.Executors; 042import java.util.concurrent.Future; 043import java.util.concurrent.RejectedExecutionException; 044import java.util.concurrent.ScheduledExecutorService; 045import java.util.concurrent.ScheduledFuture; 046import java.util.concurrent.ScheduledThreadPoolExecutor; 047import java.util.concurrent.ThreadFactory; 048import java.util.concurrent.ThreadPoolExecutor; 049import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; 050import java.util.concurrent.TimeUnit; 051import java.util.concurrent.TimeoutException; 052import javax.annotation.concurrent.GuardedBy; 053 054/** 055 * Factory and utility methods for {@link java.util.concurrent.Executor}, {@link ExecutorService}, 056 * and {@link ThreadFactory}. 057 * 058 * @author Eric Fellheimer 059 * @author Kyle Littlefield 060 * @author Justin Mahoney 061 * @since 3.0 062 */ 063@GwtCompatible(emulated = true) 064public final class MoreExecutors { 065 private MoreExecutors() {} 066 067 /** 068 * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application 069 * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their 070 * completion. 071 * 072 * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}. 073 * 074 * @param executor the executor to modify to make sure it exits when the application is finished 075 * @param terminationTimeout how long to wait for the executor to finish before terminating the 076 * JVM 077 * @param timeUnit unit of time for the time parameter 078 * @return an unmodifiable version of the input which will not hang the JVM 079 */ 080 @Beta 081 @GwtIncompatible // TODO 082 public static ExecutorService getExitingExecutorService( 083 ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { 084 return new Application().getExitingExecutorService(executor, terminationTimeout, timeUnit); 085 } 086 087 /** 088 * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when 089 * the application is complete. It does so by using daemon threads and adding a shutdown hook to 090 * wait for their completion. 091 * 092 * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}. 093 * 094 * @param executor the executor to modify to make sure it exits when the application is finished 095 * @param terminationTimeout how long to wait for the executor to finish before terminating the 096 * JVM 097 * @param timeUnit unit of time for the time parameter 098 * @return an unmodifiable version of the input which will not hang the JVM 099 */ 100 @Beta 101 @GwtIncompatible // TODO 102 public static ScheduledExecutorService getExitingScheduledExecutorService( 103 ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { 104 return new Application() 105 .getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit); 106 } 107 108 /** 109 * Add a shutdown hook to wait for thread completion in the given {@link ExecutorService service}. 110 * This is useful if the given service uses daemon threads, and we want to keep the JVM from 111 * exiting immediately on shutdown, instead giving these daemon threads a chance to terminate 112 * normally. 113 * 114 * @param service ExecutorService which uses daemon threads 115 * @param terminationTimeout how long to wait for the executor to finish before terminating the 116 * JVM 117 * @param timeUnit unit of time for the time parameter 118 */ 119 @Beta 120 @GwtIncompatible // TODO 121 public static void addDelayedShutdownHook( 122 ExecutorService service, long terminationTimeout, TimeUnit timeUnit) { 123 new Application().addDelayedShutdownHook(service, terminationTimeout, timeUnit); 124 } 125 126 /** 127 * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application 128 * is complete. It does so by using daemon threads and adding a shutdown hook to wait for their 129 * completion. 130 * 131 * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor 132 * has not finished its work. 133 * 134 * <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}. 135 * 136 * @param executor the executor to modify to make sure it exits when the application is finished 137 * @return an unmodifiable version of the input which will not hang the JVM 138 */ 139 @Beta 140 @GwtIncompatible // concurrency 141 public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) { 142 return new Application().getExitingExecutorService(executor); 143 } 144 145 /** 146 * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when 147 * the application is complete. It does so by using daemon threads and adding a shutdown hook to 148 * wait for their completion. 149 * 150 * <p>This method waits 120 seconds before continuing with JVM termination, even if the executor 151 * has not finished its work. 152 * 153 * <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}. 154 * 155 * @param executor the executor to modify to make sure it exits when the application is finished 156 * @return an unmodifiable version of the input which will not hang the JVM 157 */ 158 @Beta 159 @GwtIncompatible // TODO 160 public static ScheduledExecutorService getExitingScheduledExecutorService( 161 ScheduledThreadPoolExecutor executor) { 162 return new Application().getExitingScheduledExecutorService(executor); 163 } 164 165 /** Represents the current application to register shutdown hooks. */ 166 @GwtIncompatible // TODO 167 @VisibleForTesting 168 static class Application { 169 170 final ExecutorService getExitingExecutorService( 171 ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { 172 useDaemonThreadFactory(executor); 173 ExecutorService service = Executors.unconfigurableExecutorService(executor); 174 addDelayedShutdownHook(service, terminationTimeout, timeUnit); 175 return service; 176 } 177 178 final ScheduledExecutorService getExitingScheduledExecutorService( 179 ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { 180 useDaemonThreadFactory(executor); 181 ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor); 182 addDelayedShutdownHook(service, terminationTimeout, timeUnit); 183 return service; 184 } 185 186 final void addDelayedShutdownHook( 187 final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) { 188 checkNotNull(service); 189 checkNotNull(timeUnit); 190 addShutdownHook( 191 MoreExecutors.newThread( 192 "DelayedShutdownHook-for-" + service, 193 new Runnable() { 194 @Override 195 public void run() { 196 try { 197 // We'd like to log progress and failures that may arise in the 198 // following code, but unfortunately the behavior of logging 199 // is undefined in shutdown hooks. 200 // This is because the logging code installs a shutdown hook of its 201 // own. See Cleaner class inside {@link LogManager}. 202 service.shutdown(); 203 service.awaitTermination(terminationTimeout, timeUnit); 204 } catch (InterruptedException ignored) { 205 // We're shutting down anyway, so just ignore. 206 } 207 } 208 })); 209 } 210 211 final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) { 212 return getExitingExecutorService(executor, 120, TimeUnit.SECONDS); 213 } 214 215 final ScheduledExecutorService getExitingScheduledExecutorService( 216 ScheduledThreadPoolExecutor executor) { 217 return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS); 218 } 219 220 @VisibleForTesting 221 void addShutdownHook(Thread hook) { 222 Runtime.getRuntime().addShutdownHook(hook); 223 } 224 } 225 226 @GwtIncompatible // TODO 227 private static void useDaemonThreadFactory(ThreadPoolExecutor executor) { 228 executor.setThreadFactory( 229 new ThreadFactoryBuilder() 230 .setDaemon(true) 231 .setThreadFactory(executor.getThreadFactory()) 232 .build()); 233 } 234 235 // See newDirectExecutorService javadoc for behavioral notes. 236 @GwtIncompatible // TODO 237 private static final class DirectExecutorService extends AbstractListeningExecutorService { 238 /** 239 * Lock used whenever accessing the state variables (runningTasks, shutdown) of the executor 240 */ 241 private final Object lock = new Object(); 242 243 /* 244 * Conceptually, these two variables describe the executor being in 245 * one of three states: 246 * - Active: shutdown == false 247 * - Shutdown: runningTasks > 0 and shutdown == true 248 * - Terminated: runningTasks == 0 and shutdown == true 249 */ 250 @GuardedBy("lock") 251 private int runningTasks = 0; 252 253 @GuardedBy("lock") 254 private boolean shutdown = false; 255 256 @Override 257 public void execute(Runnable command) { 258 startTask(); 259 try { 260 command.run(); 261 } finally { 262 endTask(); 263 } 264 } 265 266 @Override 267 public boolean isShutdown() { 268 synchronized (lock) { 269 return shutdown; 270 } 271 } 272 273 @Override 274 public void shutdown() { 275 synchronized (lock) { 276 shutdown = true; 277 if (runningTasks == 0) { 278 lock.notifyAll(); 279 } 280 } 281 } 282 283 // See newDirectExecutorService javadoc for unusual behavior of this method. 284 @Override 285 public List<Runnable> shutdownNow() { 286 shutdown(); 287 return Collections.emptyList(); 288 } 289 290 @Override 291 public boolean isTerminated() { 292 synchronized (lock) { 293 return shutdown && runningTasks == 0; 294 } 295 } 296 297 @Override 298 public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { 299 long nanos = unit.toNanos(timeout); 300 synchronized (lock) { 301 while (true) { 302 if (shutdown && runningTasks == 0) { 303 return true; 304 } else if (nanos <= 0) { 305 return false; 306 } else { 307 long now = System.nanoTime(); 308 TimeUnit.NANOSECONDS.timedWait(lock, nanos); 309 nanos -= System.nanoTime() - now; // subtract the actual time we waited 310 } 311 } 312 } 313 } 314 315 /** 316 * Checks if the executor has been shut down and increments the running task count. 317 * 318 * @throws RejectedExecutionException if the executor has been previously shutdown 319 */ 320 private void startTask() { 321 synchronized (lock) { 322 if (shutdown) { 323 throw new RejectedExecutionException("Executor already shutdown"); 324 } 325 runningTasks++; 326 } 327 } 328 329 /** 330 * Decrements the running task count. 331 */ 332 private void endTask() { 333 synchronized (lock) { 334 int numRunning = --runningTasks; 335 if (numRunning == 0) { 336 lock.notifyAll(); 337 } 338 } 339 } 340 } 341 342 /** 343 * Creates an executor service that runs each task in the thread that invokes 344 * {@code execute/submit}, as in {@link CallerRunsPolicy} This applies both to individually 345 * submitted tasks and to collections of tasks submitted via {@code invokeAll} or 346 * {@code invokeAny}. In the latter case, tasks will run serially on the calling thread. Tasks are 347 * run to completion before a {@code Future} is returned to the caller (unless the executor has 348 * been shutdown). 349 * 350 * <p>Although all tasks are immediately executed in the thread that submitted the task, this 351 * {@code ExecutorService} imposes a small locking overhead on each task submission in order to 352 * implement shutdown and termination behavior. 353 * 354 * <p>The implementation deviates from the {@code ExecutorService} specification with regards to 355 * the {@code shutdownNow} method. First, "best-effort" with regards to canceling running tasks is 356 * implemented as "no-effort". No interrupts or other attempts are made to stop threads executing 357 * tasks. Second, the returned list will always be empty, as any submitted task is considered to 358 * have started execution. This applies also to tasks given to {@code invokeAll} or 359 * {@code invokeAny} which are pending serial execution, even the subset of the tasks that have 360 * not yet started execution. It is unclear from the {@code ExecutorService} specification if 361 * these should be included, and it's much easier to implement the interpretation that they not 362 * be. Finally, a call to {@code shutdown} or {@code shutdownNow} may result in concurrent calls 363 * to {@code invokeAll/invokeAny} throwing RejectedExecutionException, although a subset of the 364 * tasks may already have been executed. 365 * 366 * @since 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0) 367 */ 368 @GwtIncompatible // TODO 369 public static ListeningExecutorService newDirectExecutorService() { 370 return new DirectExecutorService(); 371 } 372 373 /** 374 * Returns an {@link Executor} that runs each task in the thread that invokes 375 * {@link Executor#execute execute}, as in {@link CallerRunsPolicy}. 376 * 377 * <p>This instance is equivalent to: <pre> {@code 378 * final class DirectExecutor implements Executor { 379 * public void execute(Runnable r) { 380 * r.run(); 381 * } 382 * }}</pre> 383 * 384 * <p>This should be preferred to {@link #newDirectExecutorService()} because implementing the 385 * {@link ExecutorService} subinterface necessitates significant performance overhead. 386 * 387 * @since 18.0 388 */ 389 public static Executor directExecutor() { 390 return DirectExecutor.INSTANCE; 391 } 392 393 /** See {@link #directExecutor} for behavioral notes. */ 394 private enum DirectExecutor implements Executor { 395 INSTANCE; 396 397 @Override 398 public void execute(Runnable command) { 399 command.run(); 400 } 401 402 @Override 403 public String toString() { 404 return "MoreExecutors.directExecutor()"; 405 } 406 } 407 408 /** 409 * Creates an {@link ExecutorService} whose {@code submit} and {@code 410 * invokeAll} methods submit {@link ListenableFutureTask} instances to the given delegate 411 * executor. Those methods, as well as {@code execute} and {@code invokeAny}, are implemented in 412 * terms of calls to {@code 413 * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that 414 * the returned {@code ListeningExecutorService} never calls the delegate's {@code submit}, 415 * {@code invokeAll}, and {@code 416 * invokeAny} methods, so any special handling of tasks must be implemented in the delegate's 417 * {@code execute} method or by wrapping the returned {@code 418 * ListeningExecutorService}. 419 * 420 * <p>If the delegate executor was already an instance of {@code 421 * ListeningExecutorService}, it is returned untouched, and the rest of this documentation does 422 * not apply. 423 * 424 * @since 10.0 425 */ 426 @GwtIncompatible // TODO 427 public static ListeningExecutorService listeningDecorator(ExecutorService delegate) { 428 return (delegate instanceof ListeningExecutorService) 429 ? (ListeningExecutorService) delegate 430 : (delegate instanceof ScheduledExecutorService) 431 ? new ScheduledListeningDecorator((ScheduledExecutorService) delegate) 432 : new ListeningDecorator(delegate); 433 } 434 435 /** 436 * Creates a {@link ScheduledExecutorService} whose {@code submit} and {@code invokeAll} methods 437 * submit {@link ListenableFutureTask} instances to the given delegate executor. Those methods, as 438 * well as {@code execute} and {@code invokeAny}, are implemented in terms of calls to {@code 439 * delegate.execute}. All other methods are forwarded unchanged to the delegate. This implies that 440 * the returned {@code ListeningScheduledExecutorService} never calls the delegate's {@code 441 * submit}, {@code invokeAll}, and {@code invokeAny} methods, so any special handling of tasks 442 * must be implemented in the delegate's {@code execute} method or by wrapping the returned {@code 443 * ListeningScheduledExecutorService}. 444 * 445 * <p>If the delegate executor was already an instance of {@code 446 * ListeningScheduledExecutorService}, it is returned untouched, and the rest of this 447 * documentation does not apply. 448 * 449 * @since 10.0 450 */ 451 @GwtIncompatible // TODO 452 public static ListeningScheduledExecutorService listeningDecorator( 453 ScheduledExecutorService delegate) { 454 return (delegate instanceof ListeningScheduledExecutorService) 455 ? (ListeningScheduledExecutorService) delegate 456 : new ScheduledListeningDecorator(delegate); 457 } 458 459 @GwtIncompatible // TODO 460 private static class ListeningDecorator extends AbstractListeningExecutorService { 461 private final ExecutorService delegate; 462 463 ListeningDecorator(ExecutorService delegate) { 464 this.delegate = checkNotNull(delegate); 465 } 466 467 @Override 468 public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { 469 return delegate.awaitTermination(timeout, unit); 470 } 471 472 @Override 473 public final boolean isShutdown() { 474 return delegate.isShutdown(); 475 } 476 477 @Override 478 public final boolean isTerminated() { 479 return delegate.isTerminated(); 480 } 481 482 @Override 483 public final void shutdown() { 484 delegate.shutdown(); 485 } 486 487 @Override 488 public final List<Runnable> shutdownNow() { 489 return delegate.shutdownNow(); 490 } 491 492 @Override 493 public final void execute(Runnable command) { 494 delegate.execute(command); 495 } 496 } 497 498 @GwtIncompatible // TODO 499 private static final class ScheduledListeningDecorator extends ListeningDecorator 500 implements ListeningScheduledExecutorService { 501 @SuppressWarnings("hiding") 502 final ScheduledExecutorService delegate; 503 504 ScheduledListeningDecorator(ScheduledExecutorService delegate) { 505 super(delegate); 506 this.delegate = checkNotNull(delegate); 507 } 508 509 @Override 510 public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { 511 TrustedListenableFutureTask<Void> task = TrustedListenableFutureTask.create(command, null); 512 ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); 513 return new ListenableScheduledTask<Void>(task, scheduled); 514 } 515 516 @Override 517 public <V> ListenableScheduledFuture<V> schedule( 518 Callable<V> callable, long delay, TimeUnit unit) { 519 TrustedListenableFutureTask<V> task = TrustedListenableFutureTask.create(callable); 520 ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); 521 return new ListenableScheduledTask<V>(task, scheduled); 522 } 523 524 @Override 525 public ListenableScheduledFuture<?> scheduleAtFixedRate( 526 Runnable command, long initialDelay, long period, TimeUnit unit) { 527 NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); 528 ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit); 529 return new ListenableScheduledTask<Void>(task, scheduled); 530 } 531 532 @Override 533 public ListenableScheduledFuture<?> scheduleWithFixedDelay( 534 Runnable command, long initialDelay, long delay, TimeUnit unit) { 535 NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); 536 ScheduledFuture<?> scheduled = 537 delegate.scheduleWithFixedDelay(task, initialDelay, delay, unit); 538 return new ListenableScheduledTask<Void>(task, scheduled); 539 } 540 541 private static final class ListenableScheduledTask<V> 542 extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> { 543 544 private final ScheduledFuture<?> scheduledDelegate; 545 546 public ListenableScheduledTask( 547 ListenableFuture<V> listenableDelegate, ScheduledFuture<?> scheduledDelegate) { 548 super(listenableDelegate); 549 this.scheduledDelegate = scheduledDelegate; 550 } 551 552 @Override 553 public boolean cancel(boolean mayInterruptIfRunning) { 554 boolean cancelled = super.cancel(mayInterruptIfRunning); 555 if (cancelled) { 556 // Unless it is cancelled, the delegate may continue being scheduled 557 scheduledDelegate.cancel(mayInterruptIfRunning); 558 559 // TODO(user): Cancel "this" if "scheduledDelegate" is cancelled. 560 } 561 return cancelled; 562 } 563 564 @Override 565 public long getDelay(TimeUnit unit) { 566 return scheduledDelegate.getDelay(unit); 567 } 568 569 @Override 570 public int compareTo(Delayed other) { 571 return scheduledDelegate.compareTo(other); 572 } 573 } 574 575 @GwtIncompatible // TODO 576 private static final class NeverSuccessfulListenableFutureTask extends AbstractFuture<Void> 577 implements Runnable { 578 private final Runnable delegate; 579 580 public NeverSuccessfulListenableFutureTask(Runnable delegate) { 581 this.delegate = checkNotNull(delegate); 582 } 583 584 @Override 585 public void run() { 586 try { 587 delegate.run(); 588 } catch (Throwable t) { 589 setException(t); 590 throw Throwables.propagate(t); 591 } 592 } 593 } 594 } 595 596 /* 597 * This following method is a modified version of one found in 598 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30 599 * which contained the following notice: 600 * 601 * Written by Doug Lea with assistance from members of JCP JSR-166 Expert Group and released to 602 * the public domain, as explained at http://creativecommons.org/publicdomain/zero/1.0/ 603 * 604 * Other contributors include Andrew Wright, Jeffrey Hayes, Pat Fisher, Mike Judd. 605 */ 606 607 /** 608 * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService} 609 * implementations. 610 */ 611 @GwtIncompatible static <T> T invokeAnyImpl( 612 ListeningExecutorService executorService, 613 Collection<? extends Callable<T>> tasks, 614 boolean timed, 615 long timeout, 616 TimeUnit unit) 617 throws InterruptedException, ExecutionException, TimeoutException { 618 checkNotNull(executorService); 619 checkNotNull(unit); 620 int ntasks = tasks.size(); 621 checkArgument(ntasks > 0); 622 List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks); 623 BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue(); 624 long timeoutNanos = unit.toNanos(timeout); 625 626 // For efficiency, especially in executors with limited 627 // parallelism, check to see if previously submitted tasks are 628 // done before submitting more of them. This interleaving 629 // plus the exception mechanics account for messiness of main 630 // loop. 631 632 try { 633 // Record exceptions so that if we fail to obtain any 634 // result, we can throw the last exception we got. 635 ExecutionException ee = null; 636 long lastTime = timed ? System.nanoTime() : 0; 637 Iterator<? extends Callable<T>> it = tasks.iterator(); 638 639 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 640 --ntasks; 641 int active = 1; 642 643 while (true) { 644 Future<T> f = futureQueue.poll(); 645 if (f == null) { 646 if (ntasks > 0) { 647 --ntasks; 648 futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); 649 ++active; 650 } else if (active == 0) { 651 break; 652 } else if (timed) { 653 f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS); 654 if (f == null) { 655 throw new TimeoutException(); 656 } 657 long now = System.nanoTime(); 658 timeoutNanos -= now - lastTime; 659 lastTime = now; 660 } else { 661 f = futureQueue.take(); 662 } 663 } 664 if (f != null) { 665 --active; 666 try { 667 return f.get(); 668 } catch (ExecutionException eex) { 669 ee = eex; 670 } catch (RuntimeException rex) { 671 ee = new ExecutionException(rex); 672 } 673 } 674 } 675 676 if (ee == null) { 677 ee = new ExecutionException(null); 678 } 679 throw ee; 680 } finally { 681 for (Future<T> f : futures) { 682 f.cancel(true); 683 } 684 } 685 } 686 687 /** 688 * Submits the task and adds a listener that adds the future to {@code queue} when it completes. 689 */ 690 @GwtIncompatible // TODO 691 private static <T> ListenableFuture<T> submitAndAddQueueListener( 692 ListeningExecutorService executorService, 693 Callable<T> task, 694 final BlockingQueue<Future<T>> queue) { 695 final ListenableFuture<T> future = executorService.submit(task); 696 future.addListener( 697 new Runnable() { 698 @Override 699 public void run() { 700 queue.add(future); 701 } 702 }, 703 directExecutor()); 704 return future; 705 } 706 707 /** 708 * Returns a default thread factory used to create new threads. 709 * 710 * <p>On AppEngine, returns {@code ThreadManager.currentRequestThreadFactory()}. Otherwise, 711 * returns {@link Executors#defaultThreadFactory()}. 712 * 713 * @since 14.0 714 */ 715 @Beta 716 @GwtIncompatible // concurrency 717 public static ThreadFactory platformThreadFactory() { 718 if (!isAppEngine()) { 719 return Executors.defaultThreadFactory(); 720 } 721 try { 722 return (ThreadFactory) 723 Class.forName("com.google.appengine.api.ThreadManager") 724 .getMethod("currentRequestThreadFactory") 725 .invoke(null); 726 } catch (IllegalAccessException e) { 727 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 728 } catch (ClassNotFoundException e) { 729 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 730 } catch (NoSuchMethodException e) { 731 throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); 732 } catch (InvocationTargetException e) { 733 throw Throwables.propagate(e.getCause()); 734 } 735 } 736 737 @GwtIncompatible // TODO 738 private static boolean isAppEngine() { 739 if (System.getProperty("com.google.appengine.runtime.environment") == null) { 740 return false; 741 } 742 try { 743 // If the current environment is null, we're not inside AppEngine. 744 return Class.forName("com.google.apphosting.api.ApiProxy") 745 .getMethod("getCurrentEnvironment") 746 .invoke(null) 747 != null; 748 } catch (ClassNotFoundException e) { 749 // If ApiProxy doesn't exist, we're not on AppEngine at all. 750 return false; 751 } catch (InvocationTargetException e) { 752 // If ApiProxy throws an exception, we're not in a proper AppEngine environment. 753 return false; 754 } catch (IllegalAccessException e) { 755 // If the method isn't accessible, we're not on a supported version of AppEngine; 756 return false; 757 } catch (NoSuchMethodException e) { 758 // If the method doesn't exist, we're not on a supported version of AppEngine; 759 return false; 760 } 761 } 762 763 /** 764 * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} unless 765 * changing the name is forbidden by the security manager. 766 */ 767 @GwtIncompatible // concurrency 768 static Thread newThread(String name, Runnable runnable) { 769 checkNotNull(name); 770 checkNotNull(runnable); 771 Thread result = platformThreadFactory().newThread(runnable); 772 try { 773 result.setName(name); 774 } catch (SecurityException e) { 775 // OK if we can't set the name in this environment. 776 } 777 return result; 778 } 779 780 // TODO(lukes): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService? 781 // TODO(lukes): provide overloads that take constant strings? Function<Runnable, String>s to 782 // calculate names? 783 784 /** 785 * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in. 786 * 787 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 788 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 789 * prevents the renaming then it will be skipped but the tasks will still execute. 790 * 791 * 792 * @param executor The executor to decorate 793 * @param nameSupplier The source of names for each task 794 */ 795 @GwtIncompatible // concurrency 796 static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) { 797 checkNotNull(executor); 798 checkNotNull(nameSupplier); 799 if (isAppEngine()) { 800 // AppEngine doesn't support thread renaming, so don't even try 801 return executor; 802 } 803 return new Executor() { 804 @Override 805 public void execute(Runnable command) { 806 executor.execute(Callables.threadRenaming(command, nameSupplier)); 807 } 808 }; 809 } 810 811 /** 812 * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run 813 * in. 814 * 815 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 816 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 817 * prevents the renaming then it will be skipped but the tasks will still execute. 818 * 819 * 820 * @param service The executor to decorate 821 * @param nameSupplier The source of names for each task 822 */ 823 @GwtIncompatible // concurrency 824 static ExecutorService renamingDecorator( 825 final ExecutorService service, final Supplier<String> nameSupplier) { 826 checkNotNull(service); 827 checkNotNull(nameSupplier); 828 if (isAppEngine()) { 829 // AppEngine doesn't support thread renaming, so don't even try. 830 return service; 831 } 832 return new WrappingExecutorService(service) { 833 @Override 834 protected <T> Callable<T> wrapTask(Callable<T> callable) { 835 return Callables.threadRenaming(callable, nameSupplier); 836 } 837 838 @Override 839 protected Runnable wrapTask(Runnable command) { 840 return Callables.threadRenaming(command, nameSupplier); 841 } 842 }; 843 } 844 845 /** 846 * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its 847 * tasks run in. 848 * 849 * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed 850 * right before each task is run. The renaming is best effort, if a {@link SecurityManager} 851 * prevents the renaming then it will be skipped but the tasks will still execute. 852 * 853 * 854 * @param service The executor to decorate 855 * @param nameSupplier The source of names for each task 856 */ 857 @GwtIncompatible // concurrency 858 static ScheduledExecutorService renamingDecorator( 859 final ScheduledExecutorService service, final Supplier<String> nameSupplier) { 860 checkNotNull(service); 861 checkNotNull(nameSupplier); 862 if (isAppEngine()) { 863 // AppEngine doesn't support thread renaming, so don't even try. 864 return service; 865 } 866 return new WrappingScheduledExecutorService(service) { 867 @Override 868 protected <T> Callable<T> wrapTask(Callable<T> callable) { 869 return Callables.threadRenaming(callable, nameSupplier); 870 } 871 872 @Override 873 protected Runnable wrapTask(Runnable command) { 874 return Callables.threadRenaming(command, nameSupplier); 875 } 876 }; 877 } 878 879 /** 880 * Shuts down the given executor service gradually, first disabling new submissions and later, if 881 * necessary, cancelling remaining tasks. 882 * 883 * <p>The method takes the following steps: 884 * <ol> 885 * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. 886 * <li>awaits executor service termination for half of the specified timeout. 887 * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling pending 888 * tasks and interrupting running tasks. 889 * <li>awaits executor service termination for the other half of the specified timeout. 890 * </ol> 891 * 892 * <p>If, at any step of the process, the calling thread is interrupted, the method calls 893 * {@link ExecutorService#shutdownNow()} and returns. 894 * 895 * @param service the {@code ExecutorService} to shut down 896 * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate 897 * @param unit the time unit of the timeout argument 898 * @return {@code true} if the {@code ExecutorService} was terminated successfully, {@code false} 899 * if the call timed out or was interrupted 900 * @since 17.0 901 */ 902 @Beta 903 @CanIgnoreReturnValue 904 @GwtIncompatible // concurrency 905 public static boolean shutdownAndAwaitTermination( 906 ExecutorService service, long timeout, TimeUnit unit) { 907 long halfTimeoutNanos = unit.toNanos(timeout) / 2; 908 // Disable new tasks from being submitted 909 service.shutdown(); 910 try { 911 // Wait for half the duration of the timeout for existing tasks to terminate 912 if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { 913 // Cancel currently executing tasks 914 service.shutdownNow(); 915 // Wait the other half of the timeout for tasks to respond to being cancelled 916 service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); 917 } 918 } catch (InterruptedException ie) { 919 // Preserve interrupt status 920 Thread.currentThread().interrupt(); 921 // (Re-)Cancel if current thread also interrupted 922 service.shutdownNow(); 923 } 924 return service.isTerminated(); 925 } 926 927 /** 928 * Returns an Executor that will propagate {@link RejectedExecutionException} from the delegate 929 * executor to the given {@code future}. 930 * 931 * <p>Note, the returned executor can only be used once. 932 */ 933 static Executor rejectionPropagatingExecutor( 934 final Executor delegate, final AbstractFuture<?> future) { 935 checkNotNull(delegate); 936 checkNotNull(future); 937 if (delegate == directExecutor()) { 938 // directExecutor() cannot throw RejectedExecutionException 939 return delegate; 940 } 941 return new Executor() { 942 volatile boolean thrownFromDelegate = true; 943 944 @Override 945 public void execute(final Runnable command) { 946 try { 947 delegate.execute( 948 new Runnable() { 949 @Override 950 public void run() { 951 thrownFromDelegate = false; 952 command.run(); 953 } 954 }); 955 } catch (RejectedExecutionException e) { 956 if (thrownFromDelegate) { 957 // wrap exception? 958 future.setException(e); 959 } 960 // otherwise it must have been thrown from a transitive call and the delegate runnable 961 // should have handled it. 962 } 963 } 964 }; 965 } 966}