Class ThreadsPooling
- java.lang.Object
-
- com.github.javinator9889.threading.pools.ThreadsPooling
-
public class ThreadsPooling extends java.lang.ObjectThreadsPoolingprovides a fast, easy access to a pool of threads that concurrently must be running, with upper limits.It handles ThreadPoolExecutor and BlockingQueue of
Runnables, manipulating and offering access to ThreadPoolExecutor methods without high user interaction: by using the customThreadsPooling.Builder(invoked viabuilder()), 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
queueis full, aRejectedExecutionHandlersubclass will be called, with theRunnablewith the just rejected thread andThreadPoolExecutorwith the executor that rejected the thread. There are several predefined handlers with some "default" options that can satisfy daily developers work:- DEFAULT_REJECTED_EXECUTION_HANDLER
- NO_ACTION_ON_REJECTED_HANDLER
- IMMEDIATELY_RUN_ON_REJECTED_HANDLER
- WAIT_SHUTDOWN_RUN_TASK_ON_REJECTED_HANDLER
All those handlers can be access instantly from within the class and used inside the builder for using the one you prefer.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classThreadsPooling.BuilderStatic class for generating a new instance ofThreadsPooling.
-
Field Summary
Fields Modifier and Type Field Description static intDEFAULT_CORE_THREADSThe default number of threads that should be running concurrently - if needed, it can be automatically increased for filling maximum threads.static longDEFAULT_KEEP_ALIVEThe 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 intDEFAULT_MAX_THREADSThe 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 intDEFAULT_QUEUE_CAPACITYThe 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.RejectedExecutionHandlerDEFAULT_REJECTED_EXECUTION_HANDLERThe default rejected execution handler - it throws an exception (NoRejectedExecutionHandler) with all useful information obtained from the thread and the executor.static java.util.concurrent.TimeUnitDEFAULT_TIME_UNITThe default time unit for the keep alive time.static java.util.concurrent.RejectedExecutionHandlerIMMEDIATELY_RUN_ON_REJECTED_HANDLERA predefined rejected execution handler that runs the rejected thread immediately.private java.util.concurrent.ThreadPoolExecutormPoolExecutorTheThreadPoolExecutorthat manages the process running.private java.util.concurrent.BlockingQueue<java.lang.Runnable>mWorkingThreadsQueueTheBlockingQueuesynchronized with the pool executor for managing incoming threads.static java.util.concurrent.RejectedExecutionHandlerNO_ACTION_ON_REJECTED_HANDLERA predefined rejected execution handler that does nothing when a thread is rejected.static java.util.concurrent.RejectedExecutionHandlerWAIT_SHUTDOWN_RUN_TASK_ON_REJECTED_HANDLERA predefined rejected execution handler that waits until all process inside theThreadPoolExecutorfinish and then, runs the rejected thread.
-
Constructor Summary
Constructors Modifier Constructor Description privateThreadsPooling(int coreThreads, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable> workingThreadsQueue)Private constructor used byThreadsPooling.Builder- cannot be accessed from outside.privateThreadsPooling(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 byThreadsPooling.Builder- cannot be accessed from outside.privateThreadsPooling(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 byThreadsPooling.Builder- cannot be accessed from outside.privateThreadsPooling(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 byThreadsPooling.Builder- cannot be accessed from outside.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidadd(java.lang.Runnable thread)Adds a newRunnableto the queue of threads.voidadd(java.lang.Runnable... threads)Adds newRunnables to the queue of threads.static ThreadsPooling.Builderbuilder()Access theThreadsPooling.Builderclass viaThreadsPoolingfor generating a new instance of that class.intgetActiveThreadsCount()Gets approximately the number of threads currently running.longgetCompletedThreadCount()Gets the approximately amount of threads that completed its execution.intgetConcurrentThreadsRunning()Gets the amount of threads that can be running concurrently.longgetKeepAliveTime()Gets the keep alive time being used by theThreadPoolExecutorinmilliseconds.longgetKeepAliveTimeWithUnit(java.util.concurrent.TimeUnit unit)Gets the keep alive time being used by theThreadPoolExecutorin the specified time unit.intgetLargestActiveThreadsRunning()Gets the maximum amount of threads that have been running concurrently.intgetMaximumThreadsRunning()Gets the maximum amount of threads that can be running concurrently.intgetPoolSize()Returns the current number of threads in the pool.java.util.concurrent.RejectedExecutionHandlergetRejectedExecutionHandler()Gets the rejected execution handler used byThreadPoolExecutor.longgetThreadCount()Returns the approximate total number of tasks that have ever been scheduled for execution.java.util.concurrent.ThreadFactorygetThreadFactory()Gets the thread factory used byThreadPoolExecutor.java.util.concurrent.BlockingQueue<java.lang.Runnable>getWorkingThreadsQueue()Gets the queue used byThreadPoolExecutor.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.voidshutdownNotWaiting()Tries to shutdown theThreadPoolExecutor, executing the submitted process but without waiting them to finish.booleanshutdownWaitTermination()Tries to shutdown theThreadPoolExecutorwaiting until all the threads have finished, waiting100 msuntil stopping abruptly.booleanshutdownWaitTermination(long timeout, java.util.concurrent.TimeUnit waitingUnit)Tries to shutdown theThreadPoolExecutorwaiting until all the threads have finished, waitingtimeout waitingUnituntil stopping abruptly.intstart()Starts running the threads included inside the queue, by callingThreadPoolExecutor.prestartAllCoreThreads().java.lang.StringtoString()Human readable representation of this class.voidupdateConcurrentThreadsRunning(int newAmountOfThreadsRunning)It sets the new amount of threads that can be concurrently running at the same time.voidupdateKeepAliveTime(long newKeepAliveTime)It updates the default keep alive time by the provided one, using by defaultmilliseconds.voidupdateKeepAliveTime(long newKeepAliveTime, java.util.concurrent.TimeUnit newTimeUnit)It updates the default keep alive time by the provided one, using the also included time unit.voidupdateMaximumActiveThreads(int newMaximumActiveThreads)It sets the maximum new amount of threads that can be concurrently running at the same time.voidupdateRejectedExecutionHandler(java.util.concurrent.RejectedExecutionHandler newHandler)Updates the rejected execution handler.voidupdateThreadFactory(java.util.concurrent.ThreadFactory newThreadFactory)Updates the thread factory used when creating threads.
-
-
-
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
DefaultRejectedExecutionHandlerfor 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
NoRejectedExecutionHandlerfor 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
ImmediatelyRunOnRejectedExecutionHandlerfor 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 theThreadPoolExecutorfinish and then, runs the rejected thread.Refer to
RunWhenTasksFinishedOnRejectedHandlerfor more information.
-
mPoolExecutor
private java.util.concurrent.ThreadPoolExecutor mPoolExecutor
TheThreadPoolExecutorthat manages the process running.
-
mWorkingThreadsQueue
private java.util.concurrent.BlockingQueue<java.lang.Runnable> mWorkingThreadsQueue
TheBlockingQueuesynchronized 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 byThreadsPooling.Builder- cannot be accessed from outside.It has the same behaviour as calling
ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, RejectedExecutionHandler)with paramsThreadsPooling(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 thekeepAliveTime.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 byThreadsPooling.Builder- cannot be accessed from outside.It has the same behaviour as calling
ThreadsPooling(int, int, long, TimeUnit, BlockingQueue, ThreadFactory, RejectedExecutionHandler)with paramsThreadsPooling (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 thekeepAliveTime.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 byThreadsPooling.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 thekeepAliveTime.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 byThreadsPooling.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 thekeepAliveTime.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
-
builder
public static ThreadsPooling.Builder builder()
Access theThreadsPooling.Builderclass viaThreadsPoolingfor generating a new instance of that class.- Returns:
Builderobject.
-
add
public void add(@NotNull java.lang.Runnable thread)Adds a newRunnableto the queue of threads. If there is any error/exception (IllegalStateException,ClassCastException,NullPointerException,IllegalArgumentException), thenRejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)is called.- Parameters:
thread- the new thread to include for execution.
-
add
public void add(@NotNull java.lang.Runnable... threads)Adds newRunnables to the queue of threads. If there is any error/exception (IllegalStateException,ClassCastException,NullPointerException,IllegalArgumentException), thenRejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)is called, with the correspondent thread that cannot be included inside thearrayot threads.- Parameters:
threads- the new threads to include for execution.
-
start
public int start()
Starts running the threads included inside the queue, by callingThreadPoolExecutor.prestartAllCoreThreads().By default, it starts only the specified
core threads.- Returns:
intwith the amount of threads started.
-
shutdownWaitTermination
public boolean shutdownWaitTermination() throws java.lang.InterruptedExceptionTries to shutdown theThreadPoolExecutorwaiting until all the threads have finished, waiting100 msuntil stopping abruptly.- Returns:
trueif all threads finished normally,falseif 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.InterruptedExceptionTries to shutdown theThreadPoolExecutorwaiting until all the threads have finished, waitingtimeout waitingUnituntil stopping abruptly.If
timeoutis set to zero, then it will be automatically changed by100 ms.- Parameters:
timeout- waiting time until a thread is interrupted - must be zero or higher.waitingUnit- the time unit for the timeout waiting.- Returns:
trueif all threads finished normally,falseif they were interrupted by this method.- Throws:
java.lang.InterruptedException- if interrupted while waiting.
-
shutdownNotWaiting
public void shutdownNotWaiting()
Tries to shutdown theThreadPoolExecutor, 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 holdRuntimePermission("modifyThread"), or the security manager'scheckAccessmethod 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 holdRuntimePermission("modifyThread"), or the security manager'scheckAccessmethod 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
paramis 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
paramis 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 defaultmilliseconds.If you want to use a different
TimeUnit, useupdateKeepAliveTime(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 isnull, it uses the default rejected execution handler.- Parameters:
newHandler- the new rejected execution handler - usenullfor 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 anyThreadFactory.- Parameters:
newThreadFactory- the new thread factory.
-
getConcurrentThreadsRunning
public int getConcurrentThreadsRunning()
Gets the amount of threads that can be running concurrently.- Returns:
intwith 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:
intwith the maximum amount of threads that can be running concurrently.
-
getActiveThreadsCount
public int getActiveThreadsCount()
Gets approximately the number of threads currently running.- Returns:
intwith the approximately number of threads currently running.
-
getKeepAliveTime
public long getKeepAliveTime()
Gets the keep alive time being used by theThreadPoolExecutorinmilliseconds.For a different time unit, use
getKeepAliveTimeWithUnit(TimeUnit)instead.- Returns:
longwith the keep alive time in milliseconds.
-
getKeepAliveTimeWithUnit
public long getKeepAliveTimeWithUnit(@NotNull java.util.concurrent.TimeUnit unit)Gets the keep alive time being used by theThreadPoolExecutorin the specified time unit.- Parameters:
unit- the time unit for wrapping keep alive time.- Returns:
longwith the keep alive time.
-
getRejectedExecutionHandler
public java.util.concurrent.RejectedExecutionHandler getRejectedExecutionHandler()
Gets the rejected execution handler used byThreadPoolExecutor.- Returns:
RejectedExecutionHandlerwith the handler.
-
getThreadFactory
public java.util.concurrent.ThreadFactory getThreadFactory()
Gets the thread factory used byThreadPoolExecutor.- Returns:
ThreadFactorywith the factory.
-
getWorkingThreadsQueue
public java.util.concurrent.BlockingQueue<java.lang.Runnable> getWorkingThreadsQueue()
Gets the queue used byThreadPoolExecutor.- Returns:
BlockingQueuewith the queue.
-
getCompletedThreadCount
public long getCompletedThreadCount()
Gets the approximately amount of threads that completed its execution.- Returns:
longwith 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:
longwith 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:
longwith 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:
intwith the current number of threads in the pool.
-
toString
public java.lang.String toString()
Human readable representation of this class.- Overrides:
toStringin classjava.lang.Object- Returns:
Stringwith the representation.
-
-