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, ThreadAwareExecutor, 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 TypeClassDescriptionprotected static interfaceDeprecated.Nested classes/interfaces inherited from class AbstractEventExecutor
AbstractEventExecutor.LazyRunnable -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedSingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) Create a new instanceprotectedSingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, boolean supportSuspension, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instanceprotectedSingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, boolean supportSuspension, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler) protectedSingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instanceprotectedSingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler) protectedSingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) Create a new instanceprotectedSingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp, boolean supportSuspension, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instanceprotectedSingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance -
Method Summary
Modifier and TypeMethodDescriptionvoidaddShutdownHook(Runnable task) Add aRunnablewhich will be executed on shutdown of this instanceprotected voidAdd a task to the task queue, or throws aRejectedExecutionExceptionif this instance was shutdown before.protected voidInvoked before returning fromrunAllTasks()andrunAllTasks(long).booleanawaitTermination(long timeout, TimeUnit unit) protected booleanprotected booleancanSuspend(int state) protected voidcleanup()Do nothing, sub-classes may overrideprotected booleanConfirm that the shutdown if the instance should be done now!protected longReturns the absolute point in time (relative toAbstractScheduledEventExecutor.getCurrentTimeNanos()) at which the next closest scheduled task should run.protected longdelayNanos(long currentTimeNanos) Returns the amount of time left until the scheduled task with the closest dead line is executed.voidprotected intAtomically increments the counter for consecutive monitor cycles where utilization was above the scale-up threshold.protected intAtomically increments the counter for consecutive monitor cycles where utilization was below the scale-down threshold.protected longReturns the accumulated active time since the last call and resets the counter.protected longReturns the timestamp of the last known activity (tasks + I/O).protected intReturns the number of registered channels for auto-scaling related decisions.protected booleanhasTasks()booleaninEventLoop(Thread thread) protected voidInterrupt the current runningThread.invokeAll(Collection<? extends Callable<T>> tasks) invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) <T> TinvokeAny(Collection<? extends Callable<T>> tasks) <T> TinvokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) booleanbooleanReturnstrueif and only if allEventExecutors managed by thisEventExecutorGroupare being shut down gracefully or was shut down.booleanReturnstrueif theEventExecutoris considered suspended.protected booleanReturnstrueif thisSingleThreadEventExecutorsupports suspension.booleanvoidlazyExecute(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.Deprecated.Please use and overridenewTaskQueue(int).newTaskQueue(int maxPendingTasks) Create a newQueuewhich will holds the tasks to execute.protected RunnablepeekTask()intReturn the number of tasks that are pending for processing.protected RunnablepollTask()protected static RunnablepollTaskFrom(Queue<Runnable> taskQueue) protected static voidreject()protected final voidOffers the task to the associatedRejectedExecutionHandler.voidremoveShutdownHook(Runnable task) Remove a previous addedRunnableas a shutdown hookprotected booleanremoveTask(Runnable task) protected voidreportActiveIoTime(long nanos) Adds the given duration to the total active time for the current measurement window.protected voidResets the counter for consecutive busy cycles to zero.protected voidResets the counter for consecutive idle cycles to zero.protected abstract voidrun()Run the tasks in thetaskQueueprotected booleanPoll all tasks from the task queue and run them viaRunnable.run()method.protected booleanrunAllTasks(long timeoutNanos) Poll all tasks from the task queue and run them viaRunnable.run()method.protected final booleanrunAllTasksFrom(Queue<Runnable> taskQueue) Runs all tasks from the passedtaskQueue.protected final booleanrunScheduledAndExecutorTasks(int maxDrainAttempts) Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty, ormaxDrainAttemptshas been exceeded.voidshutdown()Deprecated.Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) Signals this executor that the caller wants the executor to be shut down.protected RunnabletakeTask()Take the nextRunnablefrom the task queue and so will block if no task is currently present.Future<?> Returns theFuturewhich is notified when allEventExecutors managed by thisEventExecutorGrouphave been terminated.final ThreadPropertiesbooleanTry to suspend thisEventExecutorand returntrueif suspension was successful.protected voidUpdates the internal timestamp that tells when a submitted task was executed most recently.protected booleanwakesUpForTask(Runnable task) Can be overridden to control which tasks require waking theEventExecutorthread if it is waiting so that they can be run immediately.protected voidwakeup(boolean inEventLoop) Methods inherited from class AbstractScheduledEventExecutor
afterScheduledTaskSubmitted, beforeScheduledTaskSubmitted, cancelScheduledTasks, deadlineToDelayNanos, delayNanos, fetchFromScheduledTaskQueue, getCurrentTimeNanos, hasScheduledTasks, initialNanoTime, nanoTime, nextScheduledTaskDeadlineNanos, nextScheduledTaskNano, pollScheduledTask, pollScheduledTask, schedule, schedule, scheduleAtFixedRate, scheduleWithFixedDelay, ticker, validateScheduledMethods inherited from class AbstractEventExecutor
iterator, newTaskFor, newTaskFor, next, parent, runTask, safeExecute, shutdownGracefully, shutdownNow, submit, submit, submitMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface EventExecutor
inEventLoop, isExecutorThread, newFailedFuture, newProgressivePromise, newPromise, newSucceededFuture, parentMethods inherited from interface EventExecutorGroup
iterator, next, schedule, schedule, scheduleAtFixedRate, scheduleWithFixedDelay, shutdownGracefully, shutdownNow, submit, submit, submit, tickerMethods inherited from interface Iterable
forEach, spliterator
-
Constructor Details
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) Create a new instance- Parameters:
parent- theEventExecutorGroupwhich is the parent of this instance and belongs to itthreadFactory- theThreadFactorywhich will be used for the usedThreadaddTaskWakesUp-trueif 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- theEventExecutorGroupwhich is the parent of this instance and belongs to itthreadFactory- theThreadFactorywhich will be used for the usedThreadaddTaskWakesUp-trueif 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- theRejectedExecutionHandlerto use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp, boolean supportSuspension, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance- Parameters:
parent- theEventExecutorGroupwhich is the parent of this instance and belongs to itthreadFactory- theThreadFactorywhich will be used for the usedThreadaddTaskWakesUp-trueif and only if invocation ofaddTask(Runnable)will wake up the executor threadsupportSuspension-trueif suspension of thisSingleThreadEventExecutoris supported.maxPendingTasks- the maximum number of pending tasks before new tasks will be rejected.rejectedHandler- theRejectedExecutionHandlerto use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) Create a new instance- Parameters:
parent- theEventExecutorGroupwhich is the parent of this instance and belongs to itexecutor- theExecutorwhich will be used for executingaddTaskWakesUp-trueif 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- theEventExecutorGroupwhich is the parent of this instance and belongs to itexecutor- theExecutorwhich will be used for executingaddTaskWakesUp-trueif 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- theRejectedExecutionHandlerto use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, boolean supportSuspension, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) Create a new instance- Parameters:
parent- theEventExecutorGroupwhich is the parent of this instance and belongs to itexecutor- theExecutorwhich will be used for executingaddTaskWakesUp-trueif and only if invocation ofaddTask(Runnable)will wake up the executor threadsupportSuspension-trueif suspension of thisSingleThreadEventExecutoris supported.maxPendingTasks- the maximum number of pending tasks before new tasks will be rejected.rejectedHandler- theRejectedExecutionHandlerto use.
-
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler) -
SingleThreadEventExecutor
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp, boolean supportSuspension, Queue<Runnable> taskQueue, RejectedExecutionHandler rejectedHandler)
-
-
Method Details
-
newTaskQueue
Deprecated.Please use and overridenewTaskQueue(int). -
newTaskQueue
Create a newQueuewhich will holds the tasks to execute. This default implementation will return aLinkedBlockingQueuebut if your sub-class ofSingleThreadEventExecutorwill not do any blocking calls on the thisQueueit may make sense to@Overridethis 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 nextRunnablefrom the task queue and so will block if no task is currently present.Be aware that this method will throw an
UnsupportedOperationExceptionif the task queue, which was created vianewTaskQueue(), does not implementBlockingQueue.- Returns:
nullif the executor thread has been interrupted or waken up.
-
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 aRejectedExecutionExceptionif this instance was shutdown before. -
removeTask
- See Also:
-
runAllTasks
protected boolean runAllTasks()Poll all tasks from the task queue and run them viaRunnable.run()method.- Returns:
trueif 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, ormaxDrainAttemptshas 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:
trueif at least one task was run.
-
runAllTasksFrom
-
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
protected void 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
protected long 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. -
getNumOfRegisteredChannels
protected int getNumOfRegisteredChannels()Returns the number of registered channels for auto-scaling related decisions. This is intended to be used byMultithreadEventExecutorGroupfor dynamic scaling.- Returns:
- The number of registered channels, or
-1if not applicable.
-
reportActiveIoTime
protected void reportActiveIoTime(long nanos) Adds the given duration to the total active time for the current measurement window.Note: This method is not thread-safe and must only be called from the
event loop thread.- Parameters:
nanos- The active time in nanoseconds to add.
-
getAndResetAccumulatedActiveTimeNanos
protected long getAndResetAccumulatedActiveTimeNanos()Returns the accumulated active time since the last call and resets the counter. -
getLastActivityTimeNanos
protected long getLastActivityTimeNanos()Returns the timestamp of the last known activity (tasks + I/O). -
getAndIncrementIdleCycles
protected int getAndIncrementIdleCycles()Atomically increments the counter for consecutive monitor cycles where utilization was below the scale-down threshold. This is used by the auto-scaling monitor to track sustained idleness.- Returns:
- The number of consecutive idle cycles before the increment.
-
resetIdleCycles
protected void resetIdleCycles()Resets the counter for consecutive idle cycles to zero. This is typically called when the executor's utilization is no longer considered idle, breaking the streak. -
getAndIncrementBusyCycles
protected int getAndIncrementBusyCycles()Atomically increments the counter for consecutive monitor cycles where utilization was above the scale-up threshold. This is used by the auto-scaling monitor to track a sustained high load.- Returns:
- The number of consecutive busy cycles before the increment.
-
resetBusyCycles
protected void resetBusyCycles()Resets the counter for consecutive busy cycles to zero. This is typically called when the executor's utilization is no longer considered busy, breaking the streak. -
isSuspensionSupported
protected boolean isSuspensionSupported()Returnstrueif thisSingleThreadEventExecutorsupports suspension. -
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:
inEventLoopin interfaceEventExecutor
-
addShutdownHook
-
removeShutdownHook
-
shutdownGracefully
Description copied from interface:EventExecutorGroupSignals 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:
shutdownGracefullyin 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 ofquietPeriodandtimeout- Returns:
- the
EventExecutorGroup.terminationFuture()
-
terminationFuture
Description copied from interface:EventExecutorGroupReturns theFuturewhich is notified when allEventExecutors managed by thisEventExecutorGrouphave been terminated.- Specified by:
terminationFuturein interfaceEventExecutorGroup
-
shutdown
Deprecated.- Specified by:
shutdownin interfaceEventExecutorGroup- Specified by:
shutdownin interfaceExecutorService- Specified by:
shutdownin classAbstractEventExecutor
-
isShuttingDown
public boolean isShuttingDown()Description copied from interface:EventExecutorGroupReturnstrueif and only if allEventExecutors managed by thisEventExecutorGroupare being shut down gracefully or was shut down.- Specified by:
isShuttingDownin interfaceEventExecutorGroup
-
isShutdown
public boolean isShutdown()- Specified by:
isShutdownin interfaceExecutorService
-
isTerminated
public boolean isTerminated()- Specified by:
isTerminatedin interfaceExecutorService
-
isSuspended
public boolean isSuspended()Description copied from interface:EventExecutorReturnstrueif theEventExecutoris considered suspended.- Specified by:
isSuspendedin interfaceEventExecutor- Returns:
trueif suspended,falseotherwise.
-
trySuspend
public boolean trySuspend()Description copied from interface:EventExecutorTry to suspend thisEventExecutorand returntrueif suspension was successful. Suspending anEventExecutorwill allow it to free up resources, like for example aThreadthat is backing theEventExecutor. Once anEventExecutorwas suspended it will be started again by submitting work to it via one of the following methods:Executor.execute(Runnable)EventExecutorGroup.schedule(Runnable, long, TimeUnit)EventExecutorGroup.schedule(Callable, long, TimeUnit)EventExecutorGroup.scheduleAtFixedRate(Runnable, long, long, TimeUnit)EventExecutorGroup.scheduleWithFixedDelay(Runnable, long, long, TimeUnit)
trueit might take some time for theEventExecutorto fully suspend itself.- Specified by:
trySuspendin interfaceEventExecutor- Returns:
trueif suspension was successful, otherwisefalse.
-
canSuspend
protected boolean canSuspend()- Returns:
- if suspension is possible at the moment.
-
canSuspend
protected boolean canSuspend(int state) Returnstrueif thisSingleThreadEventExecutorcan be suspended at the moment,falseotherwise. Subclasses might override this method to add extra checks.- Parameters:
state- the current internal state of theSingleThreadEventExecutor.- Returns:
- if suspension is possible at the moment.
-
confirmShutdown
protected boolean confirmShutdown()Confirm that the shutdown if the instance should be done now! -
awaitTermination
- Specified by:
awaitTerminationin interfaceExecutorService- Throws:
InterruptedException
-
execute
-
lazyExecute
Description copied from class:AbstractEventExecutorLikeExecutor.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:
lazyExecutein classAbstractEventExecutor
-
invokeAny
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException - Specified by:
invokeAnyin interfaceExecutorService- Overrides:
invokeAnyin classAbstractExecutorService- Throws:
InterruptedExceptionExecutionException
-
invokeAny
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException - Specified by:
invokeAnyin interfaceExecutorService- Overrides:
invokeAnyin classAbstractExecutorService- Throws:
InterruptedExceptionExecutionExceptionTimeoutException
-
invokeAll
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException - Specified by:
invokeAllin interfaceExecutorService- Overrides:
invokeAllin classAbstractExecutorService- Throws:
InterruptedException
-
invokeAll
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException - Specified by:
invokeAllin interfaceExecutorService- Overrides:
invokeAllin classAbstractExecutorService- Throws:
InterruptedException
-
threadProperties
Returns theThreadPropertiesof theThreadthat powers theSingleThreadEventExecutor. If theSingleThreadEventExecutoris 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 theEventExecutorthread 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.
-
wakesUpForTask(Runnable)to re-create this behaviour