@ThreadSafe @ExperimentalApi(value="https://github.com/grpc/grpc-java/issues/4984") public final class SynchronizationContext extends Object implements Executor
It doesn't own any thread. Tasks are run from caller's or caller-provided threads.
Conceptually, it is fairly accurate to think of
SynchronizationContext like a cheaper
Executors.newSingleThreadExecutor() when used for synchronization (not long-running
tasks). Both use a queue for tasks that are run in order and neither guarantee that tasks have
completed before returning from
execute(). However, the behavior does diverge if locks
are held when calling the context. So it is encouraged to avoid mixing locks and synchronization
context except via
This class is thread-safe.
|Modifier and Type||Class and Description|
Allows the user to check the status and/or cancel a task scheduled by
|Constructor and Description|
Creates a SynchronizationContext.
|Modifier and Type||Method and Description|
Run all tasks in the queue in the current thread, if no other thread is running this method.
Adds a task and run it in this synchronization context as soon as possible.
Adds a task that will be run when
Schedules a task to be added and run via
public SynchronizationContext(Thread.UncaughtExceptionHandler uncaughtExceptionHandler)
uncaughtExceptionHandler- handles exceptions thrown out of the tasks. Different from what's documented on
Thread.UncaughtExceptionHandler.uncaughtException(java.lang.Thread, java.lang.Throwable), the thread is not terminated when the handler is called.
public final void drain()
Upon returning, it guarantees that all tasks submitted by
#executeLater before it
have been or will eventually be run, while not requiring any more calls to
public final void executeLater(Runnable runnable)
This is useful for cases where you want to enqueue a task while under a lock of your own,
but don't want the tasks to be run under your lock (for fear of deadlock). You can call
executeLater(java.lang.Runnable) in the lock, and call
drain() outside the lock.
public final void execute(Runnable task)
executeLater(java.lang.Runnable)but have not been run, this method will trigger them to be run before the given task. This is equivalent to calling
executeLater(java.lang.Runnable)immediately followed by
public void throwIfNotInThisSynchronizationContext()
IllegalStateExceptionif this method is not called from this synchronization context.
public final SynchronizationContext.ScheduledHandle schedule(Runnable task, long delay, TimeUnit unit, ScheduledExecutorService timerService)
execute(java.lang.Runnable)after a delay.
task- the task being scheduled
delay- the delay
unit- the time unit for the delay
ScheduledExecutorServicethat provides delayed execution