Class SingleThreadEventExecutor

    • Field Detail

      • DEFAULT_MAX_PENDING_EXECUTOR_TASKS

        static final int DEFAULT_MAX_PENDING_EXECUTOR_TASKS
      • NOOP_TASK

        private static final java.lang.Runnable NOOP_TASK
      • STATE_UPDATER

        private static final java.util.concurrent.atomic.AtomicIntegerFieldUpdater<SingleThreadEventExecutor> STATE_UPDATER
      • taskQueue

        private final java.util.Queue<java.lang.Runnable> taskQueue
      • thread

        private volatile java.lang.Thread thread
      • executor

        private final java.util.concurrent.Executor executor
      • interrupted

        private volatile boolean interrupted
      • threadLock

        private final java.util.concurrent.CountDownLatch threadLock
      • shutdownHooks

        private final java.util.Set<java.lang.Runnable> shutdownHooks
      • addTaskWakesUp

        private final boolean addTaskWakesUp
      • maxPendingTasks

        private final int maxPendingTasks
      • lastExecutionTime

        private long lastExecutionTime
      • state

        private volatile int state
      • gracefulShutdownQuietPeriod

        private volatile long gracefulShutdownQuietPeriod
      • gracefulShutdownTimeout

        private volatile long gracefulShutdownTimeout
      • gracefulShutdownStartTime

        private long gracefulShutdownStartTime
      • terminationFuture

        private final Promise<?> terminationFuture
      • SCHEDULE_PURGE_INTERVAL

        private static final long SCHEDULE_PURGE_INTERVAL
    • Constructor Detail

      • SingleThreadEventExecutor

        protected SingleThreadEventExecutor​(EventExecutorGroup parent,
                                            java.util.concurrent.ThreadFactory threadFactory,
                                            boolean addTaskWakesUp)
        Create a new instance
        Parameters:
        parent - the EventExecutorGroup which is the parent of this instance and belongs to it
        threadFactory - the ThreadFactory which will be used for the used Thread
        addTaskWakesUp - true if and only if invocation of addTask(Runnable) will wake up the executor thread
      • SingleThreadEventExecutor

        protected SingleThreadEventExecutor​(EventExecutorGroup parent,
                                            java.util.concurrent.ThreadFactory threadFactory,
                                            boolean addTaskWakesUp,
                                            int maxPendingTasks,
                                            RejectedExecutionHandler rejectedHandler)
        Create a new instance
        Parameters:
        parent - the EventExecutorGroup which is the parent of this instance and belongs to it
        threadFactory - the ThreadFactory which will be used for the used Thread
        addTaskWakesUp - true if and only if invocation of addTask(Runnable) will wake up the executor thread
        maxPendingTasks - the maximum number of pending tasks before new tasks will be rejected.
        rejectedHandler - the RejectedExecutionHandler to use.
      • SingleThreadEventExecutor

        protected SingleThreadEventExecutor​(EventExecutorGroup parent,
                                            java.util.concurrent.Executor executor,
                                            boolean addTaskWakesUp)
        Create a new instance
        Parameters:
        parent - the EventExecutorGroup which is the parent of this instance and belongs to it
        executor - the Executor which will be used for executing
        addTaskWakesUp - true if and only if invocation of addTask(Runnable) will wake up the executor thread
      • SingleThreadEventExecutor

        protected SingleThreadEventExecutor​(EventExecutorGroup parent,
                                            java.util.concurrent.Executor executor,
                                            boolean addTaskWakesUp,
                                            int maxPendingTasks,
                                            RejectedExecutionHandler rejectedHandler)
        Create a new instance
        Parameters:
        parent - the EventExecutorGroup which is the parent of this instance and belongs to it
        executor - the Executor which will be used for executing
        addTaskWakesUp - true if and only if invocation of addTask(Runnable) will wake up the executor thread
        maxPendingTasks - the maximum number of pending tasks before new tasks will be rejected.
        rejectedHandler - the RejectedExecutionHandler to use.
      • SingleThreadEventExecutor

        protected SingleThreadEventExecutor​(EventExecutorGroup parent,
                                            java.util.concurrent.Executor executor,
                                            boolean addTaskWakesUp,
                                            java.util.Queue<java.lang.Runnable> taskQueue,
                                            RejectedExecutionHandler rejectedHandler)
    • Method Detail

      • newTaskQueue

        @Deprecated
        protected java.util.Queue<java.lang.Runnable> newTaskQueue()
        Deprecated.
        Please use and override newTaskQueue(int).
      • newTaskQueue

        protected java.util.Queue<java.lang.Runnable> newTaskQueue​(int maxPendingTasks)
        Create a new Queue which will holds the tasks to execute. This default implementation will return a LinkedBlockingQueue but if your sub-class of SingleThreadEventExecutor will not do any blocking calls on the this Queue 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 running Thread.
      • pollTask

        protected java.lang.Runnable pollTask()
        See Also:
        Queue.poll()
      • pollTaskFrom

        protected static java.lang.Runnable pollTaskFrom​(java.util.Queue<java.lang.Runnable> taskQueue)
      • takeTask

        protected java.lang.Runnable takeTask()
        Take the next Runnable 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 via newTaskQueue(), does not implement BlockingQueue.

        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

        protected java.lang.Runnable peekTask()
        See Also:
        Queue.peek()
      • hasTasks

        protected boolean hasTasks()
        See Also:
        Collection.isEmpty()
      • pendingTasks

        public int pendingTasks()
        Return the number of tasks that are pending for processing.
      • addTask

        protected void addTask​(java.lang.Runnable task)
        Add a task to the task queue, or throws a RejectedExecutionException if this instance was shutdown before.
      • offerTask

        final boolean offerTask​(java.lang.Runnable task)
      • removeTask

        protected boolean removeTask​(java.lang.Runnable task)
        See Also:
        Collection.remove(Object)
      • runAllTasks

        protected boolean runAllTasks()
        Poll all tasks from the task queue and run them via Runnable.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, or maxDrainAttempts 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

        protected final boolean runAllTasksFrom​(java.util.Queue<java.lang.Runnable> taskQueue)
        Runs all tasks from the passed taskQueue.
        Parameters:
        taskQueue - To poll and execute all tasks.
        Returns:
        true if at least one task was executed.
      • runExistingTasksFrom

        private boolean runExistingTasksFrom​(java.util.Queue<java.lang.Runnable> taskQueue)
        What ever tasks are present in taskQueue when this method is invoked will be Runnable.run().
        Parameters:
        taskQueue - the task queue to drain.
        Returns:
        true if at least Runnable.run() was called.
      • runAllTasks

        protected boolean runAllTasks​(long timeoutNanos)
        Poll all tasks from the task queue and run them via Runnable.run() method. This method stops running the tasks in the task queue and returns if it ran longer than timeoutNanos.
      • delayNanos

        protected long delayNanos​(long currentTimeNanos)
        Returns the amount of time left until the scheduled task with the closest dead line is executed.
      • updateLastExecutionTime

        protected void updateLastExecutionTime()
        Updates the internal timestamp that tells when a submitted task was executed most recently. runAllTasks() and runAllTasks(long) updates this timestamp automatically, and thus there's usually no need to call this method. However, if you take the tasks manually using takeTask() or pollTask(), 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 the taskQueue
      • cleanup

        protected void cleanup()
        Do nothing, sub-classes may override
      • wakeup

        protected void wakeup​(boolean inEventLoop)
      • inEventLoop

        public boolean inEventLoop​(java.lang.Thread thread)
        Description copied from interface: EventExecutor
        Return true if the given Thread is executed in the event loop, false otherwise.
        Specified by:
        inEventLoop in interface EventExecutor
      • addShutdownHook

        public void addShutdownHook​(java.lang.Runnable task)
        Add a Runnable which will be executed on shutdown of this instance
      • removeShutdownHook

        public void removeShutdownHook​(java.lang.Runnable task)
        Remove a previous added Runnable as a shutdown hook
      • runShutdownHooks

        private boolean runShutdownHooks()
      • shutdownGracefully

        public Future<?> shutdownGracefully​(long quietPeriod,
                                            long timeout,
                                            java.util.concurrent.TimeUnit unit)
        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 return true, and the executor prepares to shut itself down. Unlike EventExecutorGroup.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 interface EventExecutorGroup
        Parameters:
        quietPeriod - the quiet period as described in the documentation
        timeout - the maximum amount of time to wait until the executor is EventExecutorGroup.shutdown() regardless if a task was submitted during the quiet period
        unit - the unit of quietPeriod and timeout
        Returns:
        the EventExecutorGroup.terminationFuture()
      • isShutdown

        public boolean isShutdown()
        Specified by:
        isShutdown in interface java.util.concurrent.ExecutorService
      • isTerminated

        public boolean isTerminated()
        Specified by:
        isTerminated in interface java.util.concurrent.ExecutorService
      • confirmShutdown

        protected boolean confirmShutdown()
        Confirm that the shutdown if the instance should be done now!
      • awaitTermination

        public boolean awaitTermination​(long timeout,
                                        java.util.concurrent.TimeUnit unit)
                                 throws java.lang.InterruptedException
        Specified by:
        awaitTermination in interface java.util.concurrent.ExecutorService
        Throws:
        java.lang.InterruptedException
      • execute

        public void execute​(java.lang.Runnable task)
        Specified by:
        execute in interface java.util.concurrent.Executor
      • lazyExecute

        public void lazyExecute​(java.lang.Runnable task)
        Description copied from class: AbstractEventExecutor
        Like Executor.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 class AbstractEventExecutor
      • execute0

        private void execute0​(java.lang.Runnable task)
      • lazyExecute0

        private void lazyExecute0​(java.lang.Runnable task)
      • execute

        private void execute​(java.lang.Runnable task,
                             boolean immediate)
      • invokeAny

        public <T> T invokeAny​(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks)
                        throws java.lang.InterruptedException,
                               java.util.concurrent.ExecutionException
        Specified by:
        invokeAny in interface java.util.concurrent.ExecutorService
        Overrides:
        invokeAny in class java.util.concurrent.AbstractExecutorService
        Throws:
        java.lang.InterruptedException
        java.util.concurrent.ExecutionException
      • invokeAny

        public <T> T invokeAny​(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks,
                               long timeout,
                               java.util.concurrent.TimeUnit unit)
                        throws java.lang.InterruptedException,
                               java.util.concurrent.ExecutionException,
                               java.util.concurrent.TimeoutException
        Specified by:
        invokeAny in interface java.util.concurrent.ExecutorService
        Overrides:
        invokeAny in class java.util.concurrent.AbstractExecutorService
        Throws:
        java.lang.InterruptedException
        java.util.concurrent.ExecutionException
        java.util.concurrent.TimeoutException
      • invokeAll

        public <T> java.util.List<java.util.concurrent.Future<T>> invokeAll​(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks)
                                                                     throws java.lang.InterruptedException
        Specified by:
        invokeAll in interface java.util.concurrent.ExecutorService
        Overrides:
        invokeAll in class java.util.concurrent.AbstractExecutorService
        Throws:
        java.lang.InterruptedException
      • invokeAll

        public <T> java.util.List<java.util.concurrent.Future<T>> invokeAll​(java.util.Collection<? extends java.util.concurrent.Callable<T>> tasks,
                                                                            long timeout,
                                                                            java.util.concurrent.TimeUnit unit)
                                                                     throws java.lang.InterruptedException
        Specified by:
        invokeAll in interface java.util.concurrent.ExecutorService
        Overrides:
        invokeAll in class java.util.concurrent.AbstractExecutorService
        Throws:
        java.lang.InterruptedException
      • throwIfInEventLoop

        private void throwIfInEventLoop​(java.lang.String method)
      • wakesUpForTask

        protected boolean wakesUpForTask​(java.lang.Runnable task)
        Can be overridden to control which tasks require waking the EventExecutor thread if it is waiting so that they can be run immediately.
      • reject

        protected static void reject()
      • reject

        protected final void reject​(java.lang.Runnable task)
        Offers the task to the associated RejectedExecutionHandler.
        Parameters:
        task - to reject.
      • startThread

        private void startThread()
      • ensureThreadStarted

        private boolean ensureThreadStarted​(int oldState)
      • doStartThread

        private void doStartThread()
      • drainTasks

        final int drainTasks()