Class MoreExecutors
- java.lang.Object
-
- com.google.common.util.concurrent.MoreExecutors
-
@GwtCompatible(emulated=true) public final class MoreExecutors extends java.lang.Object
Factory and utility methods forExecutor,ExecutorService, andThreadFactory.- Since:
- 3.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static classMoreExecutors.ApplicationRepresents the current application to register shutdown hooks.private static classMoreExecutors.DirectExecutorServiceprivate static classMoreExecutors.ListeningDecoratorprivate static classMoreExecutors.ScheduledListeningDecorator
-
Constructor Summary
Constructors Modifier Constructor Description privateMoreExecutors()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidaddDelayedShutdownHook(java.util.concurrent.ExecutorService service, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)Add a shutdown hook to wait for thread completion in the givenservice.static voidaddDelayedShutdownHook(java.util.concurrent.ExecutorService service, java.time.Duration terminationTimeout)Add a shutdown hook to wait for thread completion in the givenservice.static java.util.concurrent.ExecutordirectExecutor()Returns anExecutorthat runs each task in the thread that invokesexecute, as inThreadPoolExecutor.CallerRunsPolicy.static java.util.concurrent.ExecutorServicegetExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor)Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete.static java.util.concurrent.ExecutorServicegetExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete.static java.util.concurrent.ExecutorServicegetExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor, java.time.Duration terminationTimeout)Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete.static java.util.concurrent.ScheduledExecutorServicegetExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor)Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete.static java.util.concurrent.ScheduledExecutorServicegetExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete.static java.util.concurrent.ScheduledExecutorServicegetExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor, java.time.Duration terminationTimeout)Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete.(package private) static <T> TinvokeAnyImpl(ListeningExecutorService executorService, java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks, boolean timed, long timeout, java.util.concurrent.TimeUnit unit)An implementation ofExecutorService.invokeAny(java.util.Collection<? extends java.util.concurrent.Callable<T>>)forListeningExecutorServiceimplementations.(package private) static <T> TinvokeAnyImpl(ListeningExecutorService executorService, java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks, boolean timed, java.time.Duration timeout)An implementation ofExecutorService.invokeAny(java.util.Collection<? extends java.util.concurrent.Callable<T>>)forListeningExecutorServiceimplementations.private static booleanisAppEngine()static ListeningExecutorServicelisteningDecorator(java.util.concurrent.ExecutorService delegate)Creates anExecutorServicewhosesubmitandinvokeAllmethods submitListenableFutureTaskinstances to the given delegate executor.static ListeningScheduledExecutorServicelisteningDecorator(java.util.concurrent.ScheduledExecutorService delegate)Creates aScheduledExecutorServicewhosesubmitandinvokeAllmethods submitListenableFutureTaskinstances to the given delegate executor.static ListeningExecutorServicenewDirectExecutorService()Creates an executor service that runs each task in the thread that invokesexecute/submit, as inThreadPoolExecutor.CallerRunsPolicyThis applies both to individually submitted tasks and to collections of tasks submitted viainvokeAllorinvokeAny.static java.util.concurrent.ExecutornewSequentialExecutor(java.util.concurrent.Executor delegate)Returns anExecutorthat runs each task executed sequentially, such that no two tasks are running concurrently.(package private) static java.lang.ThreadnewThread(java.lang.String name, java.lang.Runnable runnable)Creates a thread usingplatformThreadFactory(), and sets its name tonameunless changing the name is forbidden by the security manager.static java.util.concurrent.ThreadFactoryplatformThreadFactory()Returns a default thread factory used to create new threads.(package private) static java.util.concurrent.ExecutorrejectionPropagatingExecutor(java.util.concurrent.Executor delegate, AbstractFuture<?> future)Returns an Executor that will propagateRejectedExecutionExceptionfrom the delegate executor to the givenfuture.(package private) static java.util.concurrent.ExecutorrenamingDecorator(java.util.concurrent.Executor executor, Supplier<java.lang.String> nameSupplier)Creates anExecutorthat renames thethreadsthat its tasks run in.(package private) static java.util.concurrent.ExecutorServicerenamingDecorator(java.util.concurrent.ExecutorService service, Supplier<java.lang.String> nameSupplier)Creates anExecutorServicethat renames thethreadsthat its tasks run in.(package private) static java.util.concurrent.ScheduledExecutorServicerenamingDecorator(java.util.concurrent.ScheduledExecutorService service, Supplier<java.lang.String> nameSupplier)Creates aScheduledExecutorServicethat renames thethreadsthat its tasks run in.static booleanshutdownAndAwaitTermination(java.util.concurrent.ExecutorService service, long timeout, java.util.concurrent.TimeUnit unit)Shuts down the given executor service gradually, first disabling new submissions and later, if necessary, cancelling remaining tasks.static booleanshutdownAndAwaitTermination(java.util.concurrent.ExecutorService service, java.time.Duration timeout)Shuts down the given executor service gradually, first disabling new submissions and later, if necessary, cancelling remaining tasks.private static <T> ListenableFuture<T>submitAndAddQueueListener(ListeningExecutorService executorService, java.util.concurrent.Callable<T> task, java.util.concurrent.BlockingQueue<java.util.concurrent.Future<T>> queue)Submits the task and adds a listener that adds the future toqueuewhen it completes.private static voiduseDaemonThreadFactory(java.util.concurrent.ThreadPoolExecutor executor)
-
-
-
Method Detail
-
getExitingExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ExecutorService getExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor, java.time.Duration terminationTimeout)
Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This is mainly for fixed thread pools. See
Executors.newFixedThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finishedterminationTimeout- how long to wait for the executor to finish before terminating the JVM- Returns:
- an unmodifiable version of the input which will not hang the JVM
- Since:
- 28.0
-
getExitingExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ExecutorService getExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)
Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This is mainly for fixed thread pools. See
Executors.newFixedThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finishedterminationTimeout- how long to wait for the executor to finish before terminating the JVMtimeUnit- unit of time for the time parameter- Returns:
- an unmodifiable version of the input which will not hang the JVM
-
getExitingExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ExecutorService getExitingExecutorService(java.util.concurrent.ThreadPoolExecutor executor)
Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This method waits 120 seconds before continuing with JVM termination, even if the executor has not finished its work.
This is mainly for fixed thread pools. See
Executors.newFixedThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finished- Returns:
- an unmodifiable version of the input which will not hang the JVM
-
getExitingScheduledExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ScheduledExecutorService getExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor, java.time.Duration terminationTimeout)
Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This is mainly for fixed thread pools. See
Executors.newScheduledThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finishedterminationTimeout- how long to wait for the executor to finish before terminating the JVM- Returns:
- an unmodifiable version of the input which will not hang the JVM
- Since:
- 28.0
-
getExitingScheduledExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ScheduledExecutorService getExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)
Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This is mainly for fixed thread pools. See
Executors.newScheduledThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finishedterminationTimeout- how long to wait for the executor to finish before terminating the JVMtimeUnit- unit of time for the time parameter- Returns:
- an unmodifiable version of the input which will not hang the JVM
-
getExitingScheduledExecutorService
@Beta @GwtIncompatible public static java.util.concurrent.ScheduledExecutorService getExitingScheduledExecutorService(java.util.concurrent.ScheduledThreadPoolExecutor executor)
Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion.This method waits 120 seconds before continuing with JVM termination, even if the executor has not finished its work.
This is mainly for fixed thread pools. See
Executors.newScheduledThreadPool(int).- Parameters:
executor- the executor to modify to make sure it exits when the application is finished- Returns:
- an unmodifiable version of the input which will not hang the JVM
-
addDelayedShutdownHook
@Beta @GwtIncompatible public static void addDelayedShutdownHook(java.util.concurrent.ExecutorService service, java.time.Duration terminationTimeout)
Add a shutdown hook to wait for thread completion in the givenservice. This is useful if the given service uses daemon threads, and we want to keep the JVM from exiting immediately on shutdown, instead giving these daemon threads a chance to terminate normally.- Parameters:
service- ExecutorService which uses daemon threadsterminationTimeout- how long to wait for the executor to finish before terminating the JVM- Since:
- 28.0
-
addDelayedShutdownHook
@Beta @GwtIncompatible public static void addDelayedShutdownHook(java.util.concurrent.ExecutorService service, long terminationTimeout, java.util.concurrent.TimeUnit timeUnit)
Add a shutdown hook to wait for thread completion in the givenservice. This is useful if the given service uses daemon threads, and we want to keep the JVM from exiting immediately on shutdown, instead giving these daemon threads a chance to terminate normally.- Parameters:
service- ExecutorService which uses daemon threadsterminationTimeout- how long to wait for the executor to finish before terminating the JVMtimeUnit- unit of time for the time parameter
-
useDaemonThreadFactory
@GwtIncompatible private static void useDaemonThreadFactory(java.util.concurrent.ThreadPoolExecutor executor)
-
newDirectExecutorService
@GwtIncompatible public static ListeningExecutorService newDirectExecutorService()
Creates an executor service that runs each task in the thread that invokesexecute/submit, as inThreadPoolExecutor.CallerRunsPolicyThis applies both to individually submitted tasks and to collections of tasks submitted viainvokeAllorinvokeAny. In the latter case, tasks will run serially on the calling thread. Tasks are run to completion before aFutureis returned to the caller (unless the executor has been shutdown).Although all tasks are immediately executed in the thread that submitted the task, this
ExecutorServiceimposes a small locking overhead on each task submission in order to implement shutdown and termination behavior.The implementation deviates from the
ExecutorServicespecification with regards to theshutdownNowmethod. First, "best-effort" with regards to canceling running tasks is implemented as "no-effort". No interrupts or other attempts are made to stop threads executing tasks. Second, the returned list will always be empty, as any submitted task is considered to have started execution. This applies also to tasks given toinvokeAllorinvokeAnywhich are pending serial execution, even the subset of the tasks that have not yet started execution. It is unclear from theExecutorServicespecification if these should be included, and it's much easier to implement the interpretation that they not be. Finally, a call toshutdownorshutdownNowmay result in concurrent calls toinvokeAll/invokeAnythrowing RejectedExecutionException, although a subset of the tasks may already have been executed.- Since:
- 18.0 (present as MoreExecutors.sameThreadExecutor() since 10.0)
-
directExecutor
public static java.util.concurrent.Executor directExecutor()
Returns anExecutorthat runs each task in the thread that invokesexecute, as inThreadPoolExecutor.CallerRunsPolicy.This instance is equivalent to:
final class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }This should be preferred to
newDirectExecutorService()because implementing theExecutorServicesubinterface necessitates significant performance overhead.- Since:
- 18.0
-
newSequentialExecutor
@Beta @GwtIncompatible public static java.util.concurrent.Executor newSequentialExecutor(java.util.concurrent.Executor delegate)
Returns anExecutorthat runs each task executed sequentially, such that no two tasks are running concurrently. Submitted tasks have a happens-before order as defined in the Java Language Specification.The executor uses
delegatein order toexecuteeach task in turn, and does not create any threads of its own.After execution begins on a thread from the
delegateExecutor, tasks are polled and executed from a task queue until there are no more tasks. The thread will not be released until there are no more tasks to run.If a task is submitted while a thread is executing tasks from the task queue, the thread will not be released until that submitted task is also complete.
If a task is interrupted while a task is running:
- execution will not stop until the task queue is empty.
- tasks will begin execution with the thread marked as not interrupted - any interruption applies only to the task that was running at the point of interruption.
- if the thread was interrupted before the SequentialExecutor's worker begins execution,
the interrupt will be restored to the thread after it completes so that its
delegateExecutor may process the interrupt. - subtasks are run with the thread uninterrupted and interrupts received during execution of a task are ignored.
RuntimeExceptions thrown by tasks are simply logged and the executor keeps trucking. If anErroris thrown, the error will propagate and execution will stop until the next time a task is submitted.When an
Erroris thrown by an executed task, previously submitted tasks may never run. An attempt will be made to restart execution on the next call toexecute. If thedelegatehas begun to reject execution, the previously submitted tasks may never run, despite not throwing a RejectedExecutionException synchronously with the call toexecute. If this behaviour is problematic, use an Executor with a single thread (e.g.Executors.newSingleThreadExecutor()).- Since:
- 23.3 (since 23.1 as
sequentialExecutor)
-
listeningDecorator
@GwtIncompatible public static ListeningExecutorService listeningDecorator(java.util.concurrent.ExecutorService delegate)
Creates anExecutorServicewhosesubmitandinvokeAllmethods submitListenableFutureTaskinstances to the given delegate executor. Those methods, as well asexecuteandinvokeAny, are implemented in terms of calls todelegate.execute. All other methods are forwarded unchanged to the delegate. This implies that the returnedListeningExecutorServicenever calls the delegate'ssubmit,invokeAll, andinvokeAnymethods, so any special handling of tasks must be implemented in the delegate'sexecutemethod or by wrapping the returnedListeningExecutorService.If the delegate executor was already an instance of
ListeningExecutorService, it is returned untouched, and the rest of this documentation does not apply.- Since:
- 10.0
-
listeningDecorator
@GwtIncompatible public static ListeningScheduledExecutorService listeningDecorator(java.util.concurrent.ScheduledExecutorService delegate)
Creates aScheduledExecutorServicewhosesubmitandinvokeAllmethods submitListenableFutureTaskinstances to the given delegate executor. Those methods, as well asexecuteandinvokeAny, are implemented in terms of calls todelegate.execute. All other methods are forwarded unchanged to the delegate. This implies that the returnedListeningScheduledExecutorServicenever calls the delegate'ssubmit,invokeAll, andinvokeAnymethods, so any special handling of tasks must be implemented in the delegate'sexecutemethod or by wrapping the returnedListeningScheduledExecutorService.If the delegate executor was already an instance of
ListeningScheduledExecutorService, it is returned untouched, and the rest of this documentation does not apply.- Since:
- 10.0
-
invokeAnyImpl
@GwtIncompatible static <T> T invokeAnyImpl(ListeningExecutorService executorService, java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks, boolean timed, java.time.Duration timeout) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException
An implementation ofExecutorService.invokeAny(java.util.Collection<? extends java.util.concurrent.Callable<T>>)forListeningExecutorServiceimplementations.- Throws:
java.lang.InterruptedExceptionjava.util.concurrent.ExecutionExceptionjava.util.concurrent.TimeoutException
-
invokeAnyImpl
@GwtIncompatible static <T> T invokeAnyImpl(ListeningExecutorService executorService, java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks, boolean timed, long timeout, java.util.concurrent.TimeUnit unit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException
An implementation ofExecutorService.invokeAny(java.util.Collection<? extends java.util.concurrent.Callable<T>>)forListeningExecutorServiceimplementations.- Throws:
java.lang.InterruptedExceptionjava.util.concurrent.ExecutionExceptionjava.util.concurrent.TimeoutException
-
submitAndAddQueueListener
@GwtIncompatible private static <T> ListenableFuture<T> submitAndAddQueueListener(ListeningExecutorService executorService, java.util.concurrent.Callable<T> task, java.util.concurrent.BlockingQueue<java.util.concurrent.Future<T>> queue)
Submits the task and adds a listener that adds the future toqueuewhen it completes.
-
platformThreadFactory
@Beta @GwtIncompatible public static java.util.concurrent.ThreadFactory platformThreadFactory()
Returns a default thread factory used to create new threads.On AppEngine, returns
ThreadManager.currentRequestThreadFactory(). Otherwise, returnsExecutors.defaultThreadFactory().- Since:
- 14.0
-
isAppEngine
@GwtIncompatible private static boolean isAppEngine()
-
newThread
@GwtIncompatible static java.lang.Thread newThread(java.lang.String name, java.lang.Runnable runnable)
Creates a thread usingplatformThreadFactory(), and sets its name tonameunless changing the name is forbidden by the security manager.
-
renamingDecorator
@GwtIncompatible static java.util.concurrent.Executor renamingDecorator(java.util.concurrent.Executor executor, Supplier<java.lang.String> nameSupplier)
Creates anExecutorthat renames thethreadsthat its tasks run in.The names are retrieved from the
nameSupplieron the thread that is being renamed right before each task is run. The renaming is best effort, if aSecurityManagerprevents the renaming then it will be skipped but the tasks will still execute.- Parameters:
executor- The executor to decoratenameSupplier- The source of names for each task
-
renamingDecorator
@GwtIncompatible static java.util.concurrent.ExecutorService renamingDecorator(java.util.concurrent.ExecutorService service, Supplier<java.lang.String> nameSupplier)
Creates anExecutorServicethat renames thethreadsthat its tasks run in.The names are retrieved from the
nameSupplieron the thread that is being renamed right before each task is run. The renaming is best effort, if aSecurityManagerprevents the renaming then it will be skipped but the tasks will still execute.- Parameters:
service- The executor to decoratenameSupplier- The source of names for each task
-
renamingDecorator
@GwtIncompatible static java.util.concurrent.ScheduledExecutorService renamingDecorator(java.util.concurrent.ScheduledExecutorService service, Supplier<java.lang.String> nameSupplier)
Creates aScheduledExecutorServicethat renames thethreadsthat its tasks run in.The names are retrieved from the
nameSupplieron the thread that is being renamed right before each task is run. The renaming is best effort, if aSecurityManagerprevents the renaming then it will be skipped but the tasks will still execute.- Parameters:
service- The executor to decoratenameSupplier- The source of names for each task
-
shutdownAndAwaitTermination
@Beta @GwtIncompatible public static boolean shutdownAndAwaitTermination(java.util.concurrent.ExecutorService service, java.time.Duration timeout)
Shuts down the given executor service gradually, first disabling new submissions and later, if necessary, cancelling remaining tasks.The method takes the following steps:
- calls
ExecutorService.shutdown(), disabling acceptance of new submitted tasks. - awaits executor service termination for half of the specified timeout.
- if the timeout expires, it calls
ExecutorService.shutdownNow(), cancelling pending tasks and interrupting running tasks. - awaits executor service termination for the other half of the specified timeout.
If, at any step of the process, the calling thread is interrupted, the method calls
ExecutorService.shutdownNow()and returns.- Parameters:
service- theExecutorServiceto shut downtimeout- the maximum time to wait for theExecutorServiceto terminate- Returns:
trueif theExecutorServicewas terminated successfully,falseif the call timed out or was interrupted- Since:
- 28.0
- calls
-
shutdownAndAwaitTermination
@Beta @GwtIncompatible public static boolean shutdownAndAwaitTermination(java.util.concurrent.ExecutorService service, long timeout, java.util.concurrent.TimeUnit unit)
Shuts down the given executor service gradually, first disabling new submissions and later, if necessary, cancelling remaining tasks.The method takes the following steps:
- calls
ExecutorService.shutdown(), disabling acceptance of new submitted tasks. - awaits executor service termination for half of the specified timeout.
- if the timeout expires, it calls
ExecutorService.shutdownNow(), cancelling pending tasks and interrupting running tasks. - awaits executor service termination for the other half of the specified timeout.
If, at any step of the process, the calling thread is interrupted, the method calls
ExecutorService.shutdownNow()and returns.- Parameters:
service- theExecutorServiceto shut downtimeout- the maximum time to wait for theExecutorServiceto terminateunit- the time unit of the timeout argument- Returns:
trueif theExecutorServicewas terminated successfully,falseif the call timed out or was interrupted- Since:
- 17.0
- calls
-
rejectionPropagatingExecutor
static java.util.concurrent.Executor rejectionPropagatingExecutor(java.util.concurrent.Executor delegate, AbstractFuture<?> future)Returns an Executor that will propagateRejectedExecutionExceptionfrom the delegate executor to the givenfuture.Note, the returned executor can only be used once.
-
-