Class ThreadsPooling


  • public class ThreadsPooling
    extends java.lang.Object
    ThreadsPooling provides a fast, easy access to a pool of threads that concurrently must be running, with upper limits.

    It handles ThreadPoolExecutor and BlockingQueue of Runnable s, manipulating and offering access to ThreadPoolExecutor methods without high user interaction: by using the custom ThreadsPooling.Builder (invoked via builder()), a developer can easily setup this class with the requirements needed for an optimum execution.

    In addition, this class provides some useful handlers when a new thread is rejected: for example, if th queue is full, a RejectedExecutionHandler subclass will be called, with the Runnable with the just rejected thread and ThreadPoolExecutor with the executor that rejected the thread. There are several predefined handlers with some "default" options that can satisfy daily developers work:

    All those handlers can be access instantly from within the class and used inside the builder for using the one you prefer.

    • Field Summary

      Fields 
      Modifier and Type Field Description
      static int DEFAULT_CORE_THREADS
      The default number of threads that should be running concurrently - if needed, it can be automatically increased for filling maximum threads.
      static long DEFAULT_KEEP_ALIVE
      The default keep alive time - when the number of threads is higher than the core threads, this is the time that idle threads will wait for new tasks before terminating.
      static int DEFAULT_MAX_THREADS
      The default maximum number of threads that can be concurrently running - this amount is only reached when there is a heavy load of pending threads.
      static int DEFAULT_QUEUE_CAPACITY
      The default starting queue capacity - if you know how much process you are going to run concurrently, it is better to define the queue capacity.
      static java.util.concurrent.RejectedExecutionHandler DEFAULT_REJECTED_EXECUTION_HANDLER
      The default rejected execution handler - it throws an exception (NoRejectedExecutionHandler) with all useful information obtained from the thread and the executor.
      static java.util.concurrent.TimeUnit DEFAULT_TIME_UNIT
      The default time unit for the keep alive time.
      static java.util.concurrent.RejectedExecutionHandler IMMEDIATELY_RUN_ON_REJECTED_HANDLER
      A predefined rejected execution handler that runs the rejected thread immediately.
      private java.util.concurrent.ThreadPoolExecutor mPoolExecutor
      The ThreadPoolExecutor that manages the process running.
      private java.util.concurrent.BlockingQueue<java.lang.Runnable> mWorkingThreadsQueue
      The BlockingQueue synchronized with the pool executor for managing incoming threads.
      static java.util.concurrent.RejectedExecutionHandler NO_ACTION_ON_REJECTED_HANDLER
      A predefined rejected execution handler that does nothing when a thread is rejected.
      static java.util.concurrent.RejectedExecutionHandler WAIT_SHUTDOWN_RUN_TASK_ON_REJECTED_HANDLER
      A predefined rejected execution handler that waits until all process inside the ThreadPoolExecutor finish and then, runs the rejected thread.
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      private ThreadsPooling​(int coreThreads, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue)
      Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.
      private ThreadsPooling​(int coreThreads, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue, java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
      Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.
      private ThreadsPooling​(int coreThreads, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue, java.util.concurrent.ThreadFactory factory)
      Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.
      private ThreadsPooling​(int coreThreads, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue, java.util.concurrent.ThreadFactory factory, java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
      Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void add​(java.lang.Runnable thread)
      Adds a new Runnable to the queue of threads.
      void add​(java.lang.Runnable... threads)
      Adds new Runnables to the queue of threads.
      static ThreadsPooling.Builder builder()
      Access the ThreadsPooling.Builder class via ThreadsPooling for generating a new instance of that class.
      int getActiveThreadsCount()
      Gets approximately the number of threads currently running.
      long getCompletedThreadCount()
      Gets the approximately amount of threads that completed its execution.
      int getConcurrentThreadsRunning()
      Gets the amount of threads that can be running concurrently.
      long getKeepAliveTime()
      Gets the keep alive time being used by the ThreadPoolExecutor in milliseconds.
      long getKeepAliveTimeWithUnit​(java.util.concurrent.TimeUnit unit)
      Gets the keep alive time being used by the ThreadPoolExecutor in the specified time unit.
      int getLargestActiveThreadsRunning()
      Gets the maximum amount of threads that have been running concurrently.
      int getMaximumThreadsRunning()
      Gets the maximum amount of threads that can be running concurrently.
      int getPoolSize()
      Returns the current number of threads in the pool.
      java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler()
      Gets the rejected execution handler used by ThreadPoolExecutor.
      long getThreadCount()
      Returns the approximate total number of tasks that have ever been scheduled for execution.
      java.util.concurrent.ThreadFactory getThreadFactory()
      Gets the thread factory used by ThreadPoolExecutor.
      java.util.concurrent.BlockingQueue<java.lang.Runnable> getWorkingThreadsQueue()
      Gets the queue used by ThreadPoolExecutor.
      java.util.List<java.lang.Runnable> shutdownImmediately()
      Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
      void shutdownNotWaiting()
      Tries to shutdown the ThreadPoolExecutor, executing the submitted process but without waiting them to finish.
      boolean shutdownWaitTermination()
      Tries to shutdown the ThreadPoolExecutor waiting until all the threads have finished, waiting 100 ms until stopping abruptly.
      boolean shutdownWaitTermination​(long timeout, java.util.concurrent.TimeUnit waitingUnit)
      Tries to shutdown the ThreadPoolExecutor waiting until all the threads have finished, waiting timeout waitingUnit until stopping abruptly.
      int start()
      Starts running the threads included inside the queue, by calling ThreadPoolExecutor.prestartAllCoreThreads().
      java.lang.String toString()
      Human readable representation of this class.
      void updateConcurrentThreadsRunning​(int newAmountOfThreadsRunning)
      It sets the new amount of threads that can be concurrently running at the same time.
      void updateKeepAliveTime​(long newKeepAliveTime)
      It updates the default keep alive time by the provided one, using by default milliseconds.
      void updateKeepAliveTime​(long newKeepAliveTime, java.util.concurrent.TimeUnit newTimeUnit)
      It updates the default keep alive time by the provided one, using the also included time unit.
      void updateMaximumActiveThreads​(int newMaximumActiveThreads)
      It sets the maximum new amount of threads that can be concurrently running at the same time.
      void updateRejectedExecutionHandler​(java.util.concurrent.RejectedExecutionHandler newHandler)
      Updates the rejected execution handler.
      void updateThreadFactory​(java.util.concurrent.ThreadFactory newThreadFactory)
      Updates the thread factory used when creating threads.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • DEFAULT_CORE_THREADS

        public static final int DEFAULT_CORE_THREADS
        The default number of threads that should be running concurrently - if needed, it can be automatically increased for filling maximum threads.
        See Also:
        Constant Field Values
      • DEFAULT_MAX_THREADS

        public static final int DEFAULT_MAX_THREADS
        The default maximum number of threads that can be concurrently running - this amount is only reached when there is a heavy load of pending threads.
        See Also:
        Constant Field Values
      • DEFAULT_KEEP_ALIVE

        public static final long DEFAULT_KEEP_ALIVE
        The default keep alive time - when the number of threads is higher than the core threads, this is the time that idle threads will wait for new tasks before terminating.
        See Also:
        Constant Field Values
      • DEFAULT_TIME_UNIT

        public static final java.util.concurrent.TimeUnit DEFAULT_TIME_UNIT
        The default time unit for the keep alive time.
      • DEFAULT_QUEUE_CAPACITY

        public static final int DEFAULT_QUEUE_CAPACITY
        The default starting queue capacity - if you know how much process you are going to run concurrently, it is better to define the queue capacity.
        See Also:
        Constant Field Values
      • DEFAULT_REJECTED_EXECUTION_HANDLER

        public static final java.util.concurrent.RejectedExecutionHandler DEFAULT_REJECTED_EXECUTION_HANDLER
        The default rejected execution handler - it throws an exception (NoRejectedExecutionHandler) with all useful information obtained from the thread and the executor.

        Refer to DefaultRejectedExecutionHandler for more information.

      • NO_ACTION_ON_REJECTED_HANDLER

        public static final java.util.concurrent.RejectedExecutionHandler NO_ACTION_ON_REJECTED_HANDLER
        A predefined rejected execution handler that does nothing when a thread is rejected.

        Refer to NoRejectedExecutionHandler for more information.

      • IMMEDIATELY_RUN_ON_REJECTED_HANDLER

        public static final java.util.concurrent.RejectedExecutionHandler IMMEDIATELY_RUN_ON_REJECTED_HANDLER
        A predefined rejected execution handler that runs the rejected thread immediately.

        Refer to ImmediatelyRunOnRejectedExecutionHandler for more information.

      • WAIT_SHUTDOWN_RUN_TASK_ON_REJECTED_HANDLER

        public static final java.util.concurrent.RejectedExecutionHandler WAIT_SHUTDOWN_RUN_TASK_ON_REJECTED_HANDLER
        A predefined rejected execution handler that waits until all process inside the ThreadPoolExecutor finish and then, runs the rejected thread.

        Refer to RunWhenTasksFinishedOnRejectedHandler for more information.

      • mPoolExecutor

        private java.util.concurrent.ThreadPoolExecutor mPoolExecutor
        The ThreadPoolExecutor that manages the process running.
      • mWorkingThreadsQueue

        private java.util.concurrent.BlockingQueue<java.lang.Runnable> mWorkingThreadsQueue
        The BlockingQueue synchronized with the pool executor for managing incoming threads.
    • Constructor Detail

      • ThreadsPooling

        private ThreadsPooling​(int coreThreads,
                               int maximumPoolSize,
                               long keepAliveTime,
                               java.util.concurrent.TimeUnit timeUnit,
                               java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue)
        Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.

        It has the same behaviour as calling ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler) with params ThreadsPooling(coreThreads, maximumPoolSize, keepAliveTime, timeUnit, workingThreadsQueue, DEFAULT_REJECTED_EXECUTION_HANDLER).

        Parameters:
        coreThreads - the threads that must be running concurrently.
        maximumPoolSize - the maximum threads that can be running concurrently.
        keepAliveTime - the keep alive time for idle threads to wait for running ones.
        timeUnit - the time unit that sets up the keepAliveTime.
        workingThreadsQueue - the queue of the threads that will be executed.
        See Also:
        ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler)
      • ThreadsPooling

        private ThreadsPooling​(int coreThreads,
                               int maximumPoolSize,
                               long keepAliveTime,
                               java.util.concurrent.TimeUnit timeUnit,
                               java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue,
                               java.util.concurrent.ThreadFactory factory)
        Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.

        It has the same behaviour as calling ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, ThreadFactory, RejectedExecutionHandler) with params ThreadsPooling (coreThreads, maximumPoolSize, keepAliveTime, timeUnit, workingThreadsQueue, factory, DEFAULT_REJECTED_EXECUTION_HANDLER).

        Parameters:
        coreThreads - the threads that must be running concurrently.
        maximumPoolSize - the maximum threads that can be running concurrently.
        keepAliveTime - the keep alive time for idle threads to wait for running ones.
        timeUnit - the time unit that sets up the keepAliveTime.
        workingThreadsQueue - the queue of the threads that will be executed.
        factory - the factory used for creating new threads.
        See Also:
        ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, ThreadFactory, RejectedExecutionHandler)
      • ThreadsPooling

        private ThreadsPooling​(int coreThreads,
                               int maximumPoolSize,
                               long keepAliveTime,
                               java.util.concurrent.TimeUnit timeUnit,
                               java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue,
                               java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
        Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.

        Parameters:
        coreThreads - the threads that must be running concurrently.
        maximumPoolSize - the maximum threads that can be running concurrently.
        keepAliveTime - the keep alive time for idle threads to wait for running ones.
        timeUnit - the time unit that sets up the keepAliveTime.
        workingThreadsQueue - the queue of the threads that will be executed.
        rejectedExecutionHandler - the handler used when a new thread is rejected.
        See Also:
        ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler), ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler)
      • ThreadsPooling

        private ThreadsPooling​(int coreThreads,
                               int maximumPoolSize,
                               long keepAliveTime,
                               java.util.concurrent.TimeUnit timeUnit,
                               java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue,
                               java.util.concurrent.ThreadFactory factory,
                               java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
        Private constructor used by ThreadsPooling.Builder - cannot be accessed from outside.

        Parameters:
        coreThreads - the threads that must be running concurrently.
        maximumPoolSize - the maximum threads that can be running concurrently.
        keepAliveTime - the keep alive time for idle threads to wait for running ones.
        timeUnit - the time unit that sets up the keepAliveTime.
        workingThreadsQueue - the queue of the threads that will be executed.
        factory - the factory used for creating new threads.
        rejectedExecutionHandler - the handler used when a new thread is rejected.
        See Also:
        ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler), ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue, ThreadFactory, RejectedExecutionHandler)
    • Method Detail

      • add

        public void add​(@NotNull
                        java.lang.Runnable thread)
        Adds a new Runnable to the queue of threads. If there is any error/exception (IllegalStateException, ClassCastException, NullPointerException, IllegalArgumentException), then RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) is called.
        Parameters:
        thread - the new thread to include for execution.
      • add

        public void add​(@NotNull
                        java.lang.Runnable... threads)
        Adds new Runnables to the queue of threads. If there is any error/exception (IllegalStateException, ClassCastException, NullPointerException, IllegalArgumentException), then RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) is called, with the correspondent thread that cannot be included inside the array ot threads.
        Parameters:
        threads - the new threads to include for execution.
      • start

        public int start()
        Starts running the threads included inside the queue, by calling ThreadPoolExecutor.prestartAllCoreThreads().

        By default, it starts only the specified core threads.

        Returns:
        int with the amount of threads started.
      • shutdownWaitTermination

        public boolean shutdownWaitTermination()
                                        throws java.lang.InterruptedException
        Tries to shutdown the ThreadPoolExecutor waiting until all the threads have finished, waiting 100 ms until stopping abruptly.
        Returns:
        true if all threads finished normally, false if they were interrupted by this method.
        Throws:
        java.lang.InterruptedException - if interrupted while waiting.
      • shutdownWaitTermination

        public boolean shutdownWaitTermination​(long timeout,
                                               @NotNull
                                               java.util.concurrent.TimeUnit waitingUnit)
                                        throws java.lang.InterruptedException
        Tries to shutdown the ThreadPoolExecutor waiting until all the threads have finished, waiting timeout waitingUnit until stopping abruptly.

        If timeout is set to zero, then it will be automatically changed by 100 ms.

        Parameters:
        timeout - waiting time until a thread is interrupted - must be zero or higher.
        waitingUnit - the time unit for the timeout waiting.
        Returns:
        true if all threads finished normally, false if they were interrupted by this method.
        Throws:
        java.lang.InterruptedException - if interrupted while waiting.
      • shutdownNotWaiting

        public void shutdownNotWaiting()
        Tries to shutdown the ThreadPoolExecutor, executing the submitted process but without waiting them to finish.

        For immediately finish, try using shutdownImmediately() instead.

        Throws:
        java.lang.SecurityException - if a security manager exists and shutting down this ExecutorService may manipulate threads that the caller is not permitted to modify because it does not hold RuntimePermission("modifyThread"), or the security manager's checkAccess method denies access.
      • shutdownImmediately

        public java.util.List<java.lang.Runnable> shutdownImmediately()
        Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. These tasks are drained (removed) from the task queue upon return from this method.

        This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.

        There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation interrupts tasks via Thread.interrupt; any task that fails to respond to interrupts may never terminate.

        Returns:
        list of tasks that never commenced execution.
        Throws:
        java.lang.SecurityException - if a security manager exists and shutting down this ExecutorService may manipulate threads that the caller is not permitted to modify because it does not hold RuntimePermission("modifyThread"), or the security manager's checkAccess method denies access.
      • updateConcurrentThreadsRunning

        public void updateConcurrentThreadsRunning​(int newAmountOfThreadsRunning)
        It sets the new amount of threads that can be concurrently running at the same time.

        If the new value is smaller than the current one, some threads will stop executing when they become idle.

        If bigger, any pending task will be added for execution with the new limit.

        If the param is lower than zero, it returns immediately without doing nothing. If zero, the new amount of concurrent threads will be the default value.

        Parameters:
        newAmountOfThreadsRunning - the normally amount of threads executing at the same time.
      • updateMaximumActiveThreads

        public void updateMaximumActiveThreads​(int newMaximumActiveThreads)
        It sets the maximum new amount of threads that can be concurrently running at the same time.

        If the new value is smaller than the current one, excess existing threads will stop executing when they become idle.

        If the param is lower than zero, it returns immediately without doing nothing. If zero, the new amount of concurrent threads will be the default value.

        Parameters:
        newMaximumActiveThreads - the maximum amount of threads executing at the same time.
      • updateKeepAliveTime

        public void updateKeepAliveTime​(long newKeepAliveTime)
        It updates the default keep alive time by the provided one, using by default milliseconds.

        If you want to use a different TimeUnit, use updateKeepAliveTime(long, TimeUnit) instead.

        If value is lower than zero, returns immediately without doing nothing. If zero, it will be the default value.

        Parameters:
        newKeepAliveTime - the new keep alive time.
      • updateKeepAliveTime

        public void updateKeepAliveTime​(long newKeepAliveTime,
                                        @NotNull
                                        java.util.concurrent.TimeUnit newTimeUnit)
        It updates the default keep alive time by the provided one, using the also included time unit.

        If value is lower than zero, returns immediately without doing nothing. If zero, it will be the default value.

        Parameters:
        newKeepAliveTime - the new keep alive time.
        newTimeUnit - the new time unit for the keep alive time.
      • updateRejectedExecutionHandler

        public void updateRejectedExecutionHandler​(@Nullable
                                                   java.util.concurrent.RejectedExecutionHandler newHandler)
        Updates the rejected execution handler. If it is null, it uses the default rejected execution handler.
        Parameters:
        newHandler - the new rejected execution handler - use null for the default value.
      • updateThreadFactory

        public void updateThreadFactory​(@NotNull
                                        java.util.concurrent.ThreadFactory newThreadFactory)
        Updates the thread factory used when creating threads. Use default value if you do not have any ThreadFactory.
        Parameters:
        newThreadFactory - the new thread factory.
      • getConcurrentThreadsRunning

        public int getConcurrentThreadsRunning()
        Gets the amount of threads that can be running concurrently.
        Returns:
        int with the amount of threads that can be running concurrently.
      • getMaximumThreadsRunning

        public int getMaximumThreadsRunning()
        Gets the maximum amount of threads that can be running concurrently.
        Returns:
        int with the maximum amount of threads that can be running concurrently.
      • getActiveThreadsCount

        public int getActiveThreadsCount()
        Gets approximately the number of threads currently running.
        Returns:
        int with the approximately number of threads currently running.
      • getKeepAliveTime

        public long getKeepAliveTime()
        Gets the keep alive time being used by the ThreadPoolExecutor in milliseconds.

        For a different time unit, use getKeepAliveTimeWithUnit(TimeUnit) instead.

        Returns:
        long with the keep alive time in milliseconds.
      • getKeepAliveTimeWithUnit

        public long getKeepAliveTimeWithUnit​(@NotNull
                                             java.util.concurrent.TimeUnit unit)
        Gets the keep alive time being used by the ThreadPoolExecutor in the specified time unit.
        Parameters:
        unit - the time unit for wrapping keep alive time.
        Returns:
        long with the keep alive time.
      • getRejectedExecutionHandler

        public java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler()
        Gets the rejected execution handler used by ThreadPoolExecutor.
        Returns:
        RejectedExecutionHandler with the handler.
      • getThreadFactory

        public java.util.concurrent.ThreadFactory getThreadFactory()
        Gets the thread factory used by ThreadPoolExecutor.
        Returns:
        ThreadFactory with the factory.
      • getWorkingThreadsQueue

        public java.util.concurrent.BlockingQueue<java.lang.Runnable> getWorkingThreadsQueue()
        Gets the queue used by ThreadPoolExecutor.
        Returns:
        BlockingQueue with the queue.
      • getCompletedThreadCount

        public long getCompletedThreadCount()
        Gets the approximately amount of threads that completed its execution.
        Returns:
        long with the approximately amount of threads that completed its execution.
      • getLargestActiveThreadsRunning

        public int getLargestActiveThreadsRunning()
        Gets the maximum amount of threads that have been running concurrently.
        Returns:
        long with the maximum amount of threads that have been running concurrently.
      • getThreadCount

        public long getThreadCount()
        Returns the approximate total number of tasks that have ever been scheduled for execution.
        Returns:
        long with the approximate total number of tasks that have ever been scheduled for execution.
      • getPoolSize

        public int getPoolSize()
        Returns the current number of threads in the pool.
        Returns:
        int with the current number of threads in the pool.
      • toString

        public java.lang.String toString()
        Human readable representation of this class.
        Overrides:
        toString in class java.lang.Object
        Returns:
        String with the representation.