Class NeqSimThreadPool
This class provides a centralized, managed thread pool for executing tasks asynchronously. It is
designed to replace direct new Thread(...) calls throughout the codebase, providing
better resource management and control over concurrent execution.
The thread pool size defaults to the number of available processors but can be configured. The pool uses daemon threads so it won't prevent JVM shutdown.
- Version:
- 1.0
- Author:
- esol
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static booleanWhether to allow core threads to time out and terminate when idle.private static final ThreadFactoryDefault thread factory for creating threads with proper settings.private static final intDefault pool size based on available processors.private static longKeep-alive time for idle threads in seconds.private static final ObjectLock object for thread-safe initialization.(package private) static org.apache.logging.log4j.LoggerLogger object for class.private static intMaximum queue capacity for bounded queue mode.private static ExecutorServiceThe shared ExecutorService instance.private static intConfigured pool size (can be changed before first use).private static final AtomicIntegerCounter for thread naming. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivatePrivate constructor to prevent instantiation. -
Method Summary
Modifier and TypeMethodDescriptionprivate static ExecutorServiceCreates a new thread pool with the configured size.static voidExecutes the given task sometime in the future without waiting for completion.static intGets the default pool size (number of available processors).static longGets the current keep-alive time for idle threads.static intGets the current maximum queue capacity.static ExecutorServicegetPool()Gets the shared ExecutorService instance.static intGets the current pool size configuration.static booleanChecks if core thread timeout is enabled.static booleanChecks if the pool has been shutdown.static booleanChecks if all tasks have completed following shutdown.static <T> CompletionService<T> Creates a newCompletionServicebacked by the shared thread pool.static voidResets the pool size to the default (number of available processors).static voidsetAllowCoreThreadTimeout(boolean allow) Enables or disables core thread timeout.static voidsetKeepAliveTimeSeconds(long seconds) Sets the keep-alive time for idle threads.static voidsetMaxQueueCapacity(int capacity) Sets the maximum queue capacity for bounded queue mode.static voidsetPoolSize(int size) Sets the pool size.static voidshutdown()Initiates an orderly shutdown of the thread pool.static booleanshutdownAndAwait(long timeout, TimeUnit unit) Shuts down the pool and waits for termination.static voidAttempts to stop all actively executing tasks and halts the processing of waiting tasks.static Future<?> Submits a Runnable task for execution and returns a Future representing that task.static <T> Future<T> Submits a Callable task for execution and returns a Future representing the pending result.
-
Field Details
-
logger
static org.apache.logging.log4j.Logger loggerLogger object for class. -
DEFAULT_POOL_SIZE
private static final int DEFAULT_POOL_SIZEDefault pool size based on available processors. -
pool
The shared ExecutorService instance. -
LOCK
Lock object for thread-safe initialization. -
poolSize
private static int poolSizeConfigured pool size (can be changed before first use). -
THREAD_COUNTER
Counter for thread naming. -
DEFAULT_FACTORY
Default thread factory for creating threads with proper settings. -
maxQueueCapacity
private static int maxQueueCapacityMaximum queue capacity for bounded queue mode. Set to 0 or negative for unbounded queue (default). -
allowCoreThreadTimeout
private static boolean allowCoreThreadTimeoutWhether to allow core threads to time out and terminate when idle. Default is false (threads stay alive forever). -
keepAliveTimeSeconds
private static long keepAliveTimeSecondsKeep-alive time for idle threads in seconds. Only applies when allowCoreThreadTimeout is true. Default is 60 seconds.
-
-
Constructor Details
-
NeqSimThreadPool
private NeqSimThreadPool()Private constructor to prevent instantiation.
-
-
Method Details
-
getPool
Gets the shared ExecutorService instance. The pool is lazily initialized on first access.- Returns:
- the shared
ExecutorServiceinstance
-
createPool
Creates a new thread pool with the configured size.- Returns:
- a new
ExecutorServiceinstance
-
submit
-
submit
Submits a Callable task for execution and returns a Future representing the pending result.This overload allows tasks to return results directly, which is useful for integration with external systems like Python via JPype.
- Type Parameters:
T- the type of the result- Parameters:
task- the task to submit- Returns:
- a Future representing pending completion of the task with its result
-
execute
Executes the given task sometime in the future without waiting for completion.- Parameters:
task- the task to execute
-
newCompletionService
Creates a newCompletionServicebacked by the shared thread pool.A CompletionService allows you to submit multiple tasks and retrieve their results in completion order (i.e., as each task finishes) rather than submission order. This is useful when you want to process results as soon as they become available.
Example usage:
CompletionService<Double> cs = NeqSimThreadPool.newCompletionService(); for (ProcessSystem p : processes) { cs.submit(() -> { p.run(); return p.getResult(); }); } for (int i = 0; i < processes.size(); i++) { Double result = cs.take().get(); // Results arrive in completion order System.out.println("Got result: " + result); }- Type Parameters:
T- the type of results produced by the tasks- Returns:
- a new
CompletionServicebacked by the shared thread pool
-
setPoolSize
public static void setPoolSize(int size) Sets the pool size. This must be called before the pool is first accessed. If called after the pool has been created, it will recreate the pool with the new size (existing tasks will complete).- Parameters:
size- the desired pool size (must be greater than 0)- Throws:
IllegalArgumentException- if size is less than 1
-
getPoolSize
public static int getPoolSize()Gets the current pool size configuration.- Returns:
- the configured pool size
-
setMaxQueueCapacity
public static void setMaxQueueCapacity(int capacity) Sets the maximum queue capacity for bounded queue mode.For HPC or extreme load scenarios, you can limit the queue size to prevent memory exhaustion. When the queue is full, new task submissions will be rejected with a
RejectedExecutionException.Set to 0 or negative to use unbounded queue (default). This must be called before the pool is first accessed, or the pool will be recreated.
- Parameters:
capacity- the maximum number of tasks that can wait in the queue (0 = unbounded)
-
getMaxQueueCapacity
public static int getMaxQueueCapacity()Gets the current maximum queue capacity.- Returns:
- the configured queue capacity (0 = unbounded)
-
setAllowCoreThreadTimeout
public static void setAllowCoreThreadTimeout(boolean allow) Enables or disables core thread timeout.When enabled, idle core threads will be terminated after the keep-alive time. This is useful for long-running Python processes or when memory efficiency is important.
By default, core threads stay alive forever. When enabled with the default keep-alive time of 60 seconds, idle threads will be freed after 60 seconds of inactivity.
- Parameters:
allow- true to allow core threads to timeout, false to keep them alive forever
-
isAllowCoreThreadTimeout
public static boolean isAllowCoreThreadTimeout()Checks if core thread timeout is enabled.- Returns:
- true if core threads are allowed to timeout when idle
-
setKeepAliveTimeSeconds
public static void setKeepAliveTimeSeconds(long seconds) Sets the keep-alive time for idle threads.This only takes effect when core thread timeout is enabled via
setAllowCoreThreadTimeout(boolean).- Parameters:
seconds- the time in seconds that idle threads should wait before terminating- Throws:
IllegalArgumentException- if seconds is less than 1
-
getKeepAliveTimeSeconds
public static long getKeepAliveTimeSeconds()Gets the current keep-alive time for idle threads.- Returns:
- the keep-alive time in seconds
-
getDefaultPoolSize
public static int getDefaultPoolSize()Gets the default pool size (number of available processors).- Returns:
- the default pool size
-
resetPoolSize
public static void resetPoolSize()Resets the pool size to the default (number of available processors). -
shutdown
public static void shutdown()Initiates an orderly shutdown of the thread pool. Previously submitted tasks are executed, but no new tasks will be accepted. -
shutdownNow
public static void shutdownNow()Attempts to stop all actively executing tasks and halts the processing of waiting tasks. -
shutdownAndAwait
Shuts down the pool and waits for termination.- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout argument- Returns:
trueif the pool terminated,falseif timeout elapsed
-
isShutdown
public static boolean isShutdown()Checks if the pool has been shutdown.- Returns:
trueif the pool has been shutdown
-
isTerminated
public static boolean isTerminated()Checks if all tasks have completed following shutdown.- Returns:
trueif all tasks have completed
-