Class NeqSimThreadPool

java.lang.Object
neqsim.util.NeqSimThreadPool

public final class NeqSimThreadPool extends Object
A global thread pool for NeqSim concurrent operations.

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 Details

    • logger

      static org.apache.logging.log4j.Logger logger
      Logger object for class.
    • DEFAULT_POOL_SIZE

      private static final int DEFAULT_POOL_SIZE
      Default pool size based on available processors.
    • pool

      private static volatile ExecutorService pool
      The shared ExecutorService instance.
    • LOCK

      private static final Object LOCK
      Lock object for thread-safe initialization.
    • poolSize

      private static int poolSize
      Configured pool size (can be changed before first use).
    • THREAD_COUNTER

      private static final AtomicInteger THREAD_COUNTER
      Counter for thread naming.
    • DEFAULT_FACTORY

      private static final ThreadFactory DEFAULT_FACTORY
      Default thread factory for creating threads with proper settings.
    • maxQueueCapacity

      private static int maxQueueCapacity
      Maximum queue capacity for bounded queue mode. Set to 0 or negative for unbounded queue (default).
    • allowCoreThreadTimeout

      private static boolean allowCoreThreadTimeout
      Whether to allow core threads to time out and terminate when idle. Default is false (threads stay alive forever).
    • keepAliveTimeSeconds

      private static long keepAliveTimeSeconds
      Keep-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

      public static ExecutorService getPool()
      Gets the shared ExecutorService instance. The pool is lazily initialized on first access.
      Returns:
      the shared ExecutorService instance
    • createPool

      private static ExecutorService createPool()
      Creates a new thread pool with the configured size.
      Returns:
      a new ExecutorService instance
    • submit

      public static Future<?> submit(Runnable task)
      Submits a Runnable task for execution and returns a Future representing that task.
      Parameters:
      task - the task to submit
      Returns:
      a Future representing pending completion of the task
    • submit

      public static <T> Future<T> submit(Callable<T> task)
      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

      public static void execute(Runnable task)
      Executes the given task sometime in the future without waiting for completion.
      Parameters:
      task - the task to execute
    • newCompletionService

      public static <T> CompletionService<T> newCompletionService()
      Creates a new CompletionService backed 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 CompletionService backed 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

      public static boolean shutdownAndAwait(long timeout, TimeUnit unit)
      Shuts down the pool and waits for termination.
      Parameters:
      timeout - the maximum time to wait
      unit - the time unit of the timeout argument
      Returns:
      true if the pool terminated, false if timeout elapsed
    • isShutdown

      public static boolean isShutdown()
      Checks if the pool has been shutdown.
      Returns:
      true if the pool has been shutdown
    • isTerminated

      public static boolean isTerminated()
      Checks if all tasks have completed following shutdown.
      Returns:
      true if all tasks have completed