Package io.netty.util.concurrent
Class SingleThreadEventExecutor
java.lang.Object
java.util.concurrent.AbstractExecutorService
io.netty.util.concurrent.AbstractEventExecutor
io.netty.util.concurrent.AbstractScheduledEventExecutor
io.netty.util.concurrent.SingleThreadEventExecutor
- All Implemented Interfaces:
EventExecutor
,EventExecutorGroup
,OrderedEventExecutor
,AutoCloseable
,Iterable<EventExecutor>
,Executor
,ExecutorService
,ScheduledExecutorService
- Direct Known Subclasses:
DefaultEventExecutor
,SingleThreadEventLoop
public abstract class SingleThreadEventExecutor
extends AbstractScheduledEventExecutor
implements OrderedEventExecutor
Abstract base class for
OrderedEventExecutor
's that execute all its submitted tasks in a single thread.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final class
protected static interface
Deprecated.Nested classes/interfaces inherited from class io.netty.util.concurrent.AbstractEventExecutor
AbstractEventExecutor.LazyRunnable
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final boolean
(package private) static final int
private final Executor
private long
private long
private long
private boolean
private long
private static final InternalLogger
private final int
private static final Runnable
private static final AtomicReferenceFieldUpdater
<SingleThreadEventExecutor, ThreadProperties> private final RejectedExecutionHandler
private static final long
private static final int
private static final int
private static final int
private static final int
private static final int
private int
private static final AtomicIntegerFieldUpdater
<SingleThreadEventExecutor> private final Promise
<?> private Thread
private final CountDownLatch
private ThreadProperties
Fields inherited from class io.netty.util.concurrent.AbstractScheduledEventExecutor
nextTaskId, scheduledTaskQueue, WAKEUP_TASK
Fields inherited from class io.netty.util.concurrent.AbstractEventExecutor
DEFAULT_SHUTDOWN_QUIET_PERIOD, DEFAULT_SHUTDOWN_TIMEOUT
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
SingleThreadEventExecutor
(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) Create a new instanceprotected
SingleThreadEventExecutor
(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instanceprotected
SingleThreadEventExecutor
(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler) protected
SingleThreadEventExecutor
(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) Create a new instanceprotected
SingleThreadEventExecutor
(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance -
Method Summary
Modifier and TypeMethodDescriptionvoid
addShutdownHook
(Runnable task) Add aRunnable
which will be executed on shutdown of this instanceprotected void
Add a task to the task queue, or throws aRejectedExecutionException
if this instance was shutdown before.protected void
Invoked before returning fromrunAllTasks()
andrunAllTasks(long)
.boolean
awaitTermination
(long timeout, TimeUnit unit) protected void
cleanup()
Do nothing, sub-classes may overrideprotected boolean
Confirm that the shutdown if the instance should be done now!protected long
Returns the absolute point in time (relative toAbstractScheduledEventExecutor.getCurrentTimeNanos()
) at which the next closest scheduled task should run.protected long
delayNanos
(long currentTimeNanos) Returns the amount of time left until the scheduled task with the closest dead line is executed.private void
(package private) final int
private boolean
ensureThreadStarted
(int oldState) void
private void
private void
private boolean
private boolean
protected boolean
hasTasks()
boolean
inEventLoop
(Thread thread) protected void
Interrupt the current runningThread
.invokeAll
(Collection<? extends Callable<T>> tasks) invokeAll
(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) <T> T
invokeAny
(Collection<? extends Callable<T>> tasks) <T> T
invokeAny
(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) boolean
boolean
Returnstrue
if and only if allEventExecutor
s managed by thisEventExecutorGroup
are being shut down gracefully or was shut down.boolean
void
lazyExecute
(Runnable task) LikeExecutor.execute(Runnable)
but does not guarantee the task will be run until either a non-lazy task is executed or the executor is shut down.private void
lazyExecute0
(Runnable task) Deprecated.Please use and overridenewTaskQueue(int)
.newTaskQueue
(int maxPendingTasks) Create a newQueue
which will holds the tasks to execute.(package private) final boolean
protected Runnable
peekTask()
int
Return the number of tasks that are pending for processing.protected Runnable
pollTask()
protected static Runnable
pollTaskFrom
(Queue<Runnable> taskQueue) protected static void
reject()
protected final void
Offers the task to the associatedRejectedExecutionHandler
.void
removeShutdownHook
(Runnable task) Remove a previous addedRunnable
as a shutdown hookprotected boolean
removeTask
(Runnable task) protected abstract void
run()
Run the tasks in thetaskQueue
protected boolean
Poll all tasks from the task queue and run them viaRunnable.run()
method.protected boolean
runAllTasks
(long timeoutNanos) Poll all tasks from the task queue and run them viaRunnable.run()
method.protected final boolean
runAllTasksFrom
(Queue<Runnable> taskQueue) Runs all tasks from the passedtaskQueue
.private boolean
runExistingTasksFrom
(Queue<Runnable> taskQueue) What ever tasks are present intaskQueue
when this method is invoked will beRunnable.run()
.protected final boolean
runScheduledAndExecutorTasks
(int maxDrainAttempts) Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty, ormaxDrainAttempts
has been exceeded.private boolean
void
shutdown()
Deprecated.Future
<?> shutdownGracefully
(long quietPeriod, long timeout, TimeUnit unit) Signals this executor that the caller wants the executor to be shut down.private void
protected Runnable
takeTask()
Take the nextRunnable
from the task queue and so will block if no task is currently present.Future
<?> Returns theFuture
which is notified when allEventExecutor
s managed by thisEventExecutorGroup
have been terminated.final ThreadProperties
private void
throwIfInEventLoop
(String method) protected void
Updates the internal timestamp that tells when a submitted task was executed most recently.protected boolean
wakesUpForTask
(Runnable task) Can be overridden to control which tasks require waking theEventExecutor
thread if it is waiting so that they can be run immediately.protected void
wakeup
(boolean inEventLoop) Methods inherited from class io.netty.util.concurrent.AbstractScheduledEventExecutor
afterScheduledTaskSubmitted, beforeScheduledTaskSubmitted, cancelScheduledTasks, deadlineNanos, deadlineToDelayNanos, defaultCurrentTimeNanos, getCurrentTimeNanos, hasScheduledTasks, initialNanoTime, nanoTime, nextScheduledTaskDeadlineNanos, nextScheduledTaskNano, peekScheduledTask, pollScheduledTask, pollScheduledTask, removeScheduled, schedule, schedule, scheduleAtFixedRate, scheduledTaskQueue, scheduleFromEventLoop, scheduleWithFixedDelay, validateScheduled
Methods inherited from class io.netty.util.concurrent.AbstractEventExecutor
inEventLoop, iterator, newFailedFuture, newProgressivePromise, newPromise, newSucceededFuture, newTaskFor, newTaskFor, next, parent, runTask, safeExecute, shutdownGracefully, shutdownNow, submit, submit, submit
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface io.netty.util.concurrent.EventExecutor
inEventLoop, newFailedFuture, newProgressivePromise, newPromise, newSucceededFuture, next, parent
Methods inherited from interface io.netty.util.concurrent.EventExecutorGroup
iterator, schedule, schedule, scheduleAtFixedRate, scheduleWithFixedDelay, shutdownGracefully, shutdownNow, submit, submit, submit
Methods inherited from interface java.util.concurrent.ExecutorService
close
Methods inherited from interface java.lang.Iterable
forEach, spliterator
-
Field Details
-
DEFAULT_MAX_PENDING_EXECUTOR_TASKS
static final int DEFAULT_MAX_PENDING_EXECUTOR_TASKS -
logger
-
ST_NOT_STARTED
private static final int ST_NOT_STARTED- See Also:
-
ST_STARTED
private static final int ST_STARTED- See Also:
-
ST_SHUTTING_DOWN
private static final int ST_SHUTTING_DOWN- See Also:
-
ST_SHUTDOWN
private static final int ST_SHUTDOWN- See Also:
-
ST_TERMINATED
private static final int ST_TERMINATED- See Also:
-
NOOP_TASK
-
STATE_UPDATER
-
PROPERTIES_UPDATER
private static final AtomicReferenceFieldUpdater<SingleThreadEventExecutor,ThreadProperties> PROPERTIES_UPDATER -
taskQueue
-
thread
-
threadProperties
-
executor
-
interrupted
private volatile boolean interrupted -
threadLock
-
shutdownHooks
-
addTaskWakesUp
private final boolean addTaskWakesUp -
maxPendingTasks
private final int maxPendingTasks -
rejectedExecutionHandler
-
lastExecutionTime
private long lastExecutionTime -
state
private volatile int state -
gracefulShutdownQuietPeriod
private volatile long gracefulShutdownQuietPeriod -
gracefulShutdownTimeout
private volatile long gracefulShutdownTimeout -
gracefulShutdownStartTime
private long gracefulShutdownStartTime -
terminationFuture
-
SCHEDULE_PURGE_INTERVAL
private static final long SCHEDULE_PURGE_INTERVAL
-
-
Constructor Details
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) Create a new instance- Parameters:
parent
- theEventExecutorGroup
which is the parent of this instance and belongs to itthreadFactory
- theThreadFactory
which will be used for the usedThread
addTaskWakesUp
-true
if and only if invocation ofaddTask(Runnable)
will wake up the executor thread
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance- Parameters:
parent
- theEventExecutorGroup
which is the parent of this instance and belongs to itthreadFactory
- theThreadFactory
which will be used for the usedThread
addTaskWakesUp
-true
if and only if invocation ofaddTask(Runnable)
will wake up the executor threadmaxPendingTasks
- the maximum number of pending tasks before new tasks will be rejected.rejectedHandler
- theRejectedExecutionHandler
to use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) Create a new instance- Parameters:
parent
- theEventExecutorGroup
which is the parent of this instance and belongs to itexecutor
- theExecutor
which will be used for executingaddTaskWakesUp
-true
if and only if invocation ofaddTask(Runnable)
will wake up the executor thread
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance- Parameters:
parent
- theEventExecutorGroup
which is the parent of this instance and belongs to itexecutor
- theExecutor
which will be used for executingaddTaskWakesUp
-true
if and only if invocation ofaddTask(Runnable)
will wake up the executor threadmaxPendingTasks
- the maximum number of pending tasks before new tasks will be rejected.rejectedHandler
- theRejectedExecutionHandler
to use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler)
-
-
Method Details
-
newTaskQueue
Deprecated.Please use and overridenewTaskQueue(int)
. -
newTaskQueue
Create a newQueue
which will holds the tasks to execute. This default implementation will return aLinkedBlockingQueue
but if your sub-class ofSingleThreadEventExecutor
will not do any blocking calls on the thisQueue
it may make sense to@Override
this and return some more performant implementation that does not support blocking operations at all. -
interruptThread
protected void interruptThread()Interrupt the current runningThread
. -
pollTask
- See Also:
-
pollTaskFrom
-
takeTask
Take the nextRunnable
from the task queue and so will block if no task is currently present.Be aware that this method will throw an
UnsupportedOperationException
if the task queue, which was created vianewTaskQueue()
, does not implementBlockingQueue
.- Returns:
null
if the executor thread has been interrupted or waken up.
-
fetchFromScheduledTaskQueue
private boolean fetchFromScheduledTaskQueue() -
executeExpiredScheduledTasks
private boolean executeExpiredScheduledTasks()- Returns:
true
if at least one scheduled task was executed.
-
peekTask
- See Also:
-
hasTasks
protected boolean hasTasks()- See Also:
-
pendingTasks
public int pendingTasks()Return the number of tasks that are pending for processing. -
addTask
Add a task to the task queue, or throws aRejectedExecutionException
if this instance was shutdown before. -
offerTask
-
removeTask
- See Also:
-
runAllTasks
protected boolean runAllTasks()Poll all tasks from the task queue and run them viaRunnable.run()
method.- Returns:
true
if and only if at least one task was run
-
runScheduledAndExecutorTasks
protected final boolean runScheduledAndExecutorTasks(int maxDrainAttempts) Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty, ormaxDrainAttempts
has been exceeded.- Parameters:
maxDrainAttempts
- The maximum amount of times this method attempts to drain from queues. This is to prevent continuous task execution and scheduling from preventing the EventExecutor thread to make progress and return to the selector mechanism to process inbound I/O events.- Returns:
true
if at least one task was run.
-
runAllTasksFrom
Runs all tasks from the passedtaskQueue
.- Parameters:
taskQueue
- To poll and execute all tasks.- Returns:
true
if at least one task was executed.
-
runExistingTasksFrom
What ever tasks are present intaskQueue
when this method is invoked will beRunnable.run()
.- Parameters:
taskQueue
- the task queue to drain.- Returns:
true
if at leastRunnable.run()
was called.
-
runAllTasks
protected boolean runAllTasks(long timeoutNanos) Poll all tasks from the task queue and run them viaRunnable.run()
method. This method stops running the tasks in the task queue and returns if it ran longer thantimeoutNanos
. -
afterRunningAllTasks
Invoked before returning fromrunAllTasks()
andrunAllTasks(long)
. -
delayNanos
protected long delayNanos(long currentTimeNanos) Returns the amount of time left until the scheduled task with the closest dead line is executed. -
deadlineNanos
Returns the absolute point in time (relative toAbstractScheduledEventExecutor.getCurrentTimeNanos()
) at which the next closest scheduled task should run. -
updateLastExecutionTime
protected void updateLastExecutionTime()Updates the internal timestamp that tells when a submitted task was executed most recently.runAllTasks()
andrunAllTasks(long)
updates this timestamp automatically, and thus there's usually no need to call this method. However, if you take the tasks manually usingtakeTask()
orpollTask()
, you have to call this method at the end of task execution loop for accurate quiet period checks. -
run
protected abstract void run()Run the tasks in thetaskQueue
-
cleanup
protected void cleanup()Do nothing, sub-classes may override -
wakeup
protected void wakeup(boolean inEventLoop) -
inEventLoop
Description copied from interface:EventExecutor
- Specified by:
inEventLoop
in interfaceEventExecutor
-
addShutdownHook
Add aRunnable
which will be executed on shutdown of this instance -
removeShutdownHook
Remove a previous addedRunnable
as a shutdown hook -
runShutdownHooks
private boolean runShutdownHooks() -
shutdownGracefully
Description copied from interface:EventExecutorGroup
Signals this executor that the caller wants the executor to be shut down. Once this method is called,EventExecutorGroup.isShuttingDown()
starts to returntrue
, and the executor prepares to shut itself down. UnlikeEventExecutorGroup.shutdown()
, graceful shutdown ensures that no tasks are submitted for 'the quiet period' (usually a couple seconds) before it shuts itself down. If a task is submitted during the quiet period, it is guaranteed to be accepted and the quiet period will start over.- Specified by:
shutdownGracefully
in interfaceEventExecutorGroup
- Parameters:
quietPeriod
- the quiet period as described in the documentationtimeout
- the maximum amount of time to wait until the executor is EventExecutorGroup.shutdown() regardless if a task was submitted during the quiet periodunit
- the unit ofquietPeriod
andtimeout
- Returns:
- the
EventExecutorGroup.terminationFuture()
-
terminationFuture
Description copied from interface:EventExecutorGroup
Returns theFuture
which is notified when allEventExecutor
s managed by thisEventExecutorGroup
have been terminated.- Specified by:
terminationFuture
in interfaceEventExecutorGroup
-
shutdown
Deprecated.- Specified by:
shutdown
in interfaceEventExecutorGroup
- Specified by:
shutdown
in interfaceExecutorService
- Specified by:
shutdown
in classAbstractEventExecutor
-
isShuttingDown
public boolean isShuttingDown()Description copied from interface:EventExecutorGroup
Returnstrue
if and only if allEventExecutor
s managed by thisEventExecutorGroup
are being shut down gracefully or was shut down.- Specified by:
isShuttingDown
in interfaceEventExecutorGroup
-
isShutdown
public boolean isShutdown()- Specified by:
isShutdown
in interfaceExecutorService
-
isTerminated
public boolean isTerminated()- Specified by:
isTerminated
in interfaceExecutorService
-
confirmShutdown
protected boolean confirmShutdown()Confirm that the shutdown if the instance should be done now! -
awaitTermination
- Specified by:
awaitTermination
in interfaceExecutorService
- Throws:
InterruptedException
-
execute
-
lazyExecute
Description copied from class:AbstractEventExecutor
LikeExecutor.execute(Runnable)
but does not guarantee the task will be run until either a non-lazy task is executed or the executor is shut down.The default implementation just delegates to
Executor.execute(Runnable)
.- Overrides:
lazyExecute
in classAbstractEventExecutor
-
execute0
-
lazyExecute0
-
execute
-
invokeAny
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException - Specified by:
invokeAny
in interfaceExecutorService
- Overrides:
invokeAny
in classAbstractExecutorService
- Throws:
InterruptedException
ExecutionException
-
invokeAny
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException - Specified by:
invokeAny
in interfaceExecutorService
- Overrides:
invokeAny
in classAbstractExecutorService
- Throws:
InterruptedException
ExecutionException
TimeoutException
-
invokeAll
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException - Specified by:
invokeAll
in interfaceExecutorService
- Overrides:
invokeAll
in classAbstractExecutorService
- Throws:
InterruptedException
-
invokeAll
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException - Specified by:
invokeAll
in interfaceExecutorService
- Overrides:
invokeAll
in classAbstractExecutorService
- Throws:
InterruptedException
-
throwIfInEventLoop
-
threadProperties
Returns theThreadProperties
of theThread
that powers theSingleThreadEventExecutor
. If theSingleThreadEventExecutor
is not started yet, this operation will start it and block until it is fully started. -
wakesUpForTask
Can be overridden to control which tasks require waking theEventExecutor
thread if it is waiting so that they can be run immediately. -
reject
protected static void reject() -
reject
Offers the task to the associatedRejectedExecutionHandler
.- Parameters:
task
- to reject.
-
startThread
private void startThread() -
ensureThreadStarted
private boolean ensureThreadStarted(int oldState) -
doStartThread
private void doStartThread() -
drainTasks
final int drainTasks()
-
wakesUpForTask(java.lang.Runnable)
to re-create this behaviour