The ThreadManagerPool utility class centralizes thread management and task scheduling in a Java application. It provides a fixed-size thread pool for asynchronous tasks and a scheduled thread pool for periodic executions. Additionally, it handles graceful thread shutdown and manages exceptions in tasks.
ThreadManagerPool simplifies managing concurrent tasks in an application. By providing a shared pool of threads and automated exception handling, it reduces boilerplate code and ensures efficient resource usage.
- Asynchronous Task Execution: Run tasks in parallel using a fixed-size thread pool.
- Periodic Task Scheduling: Execute tasks at fixed intervals with a scheduled thread pool.
- Graceful Shutdown: Ensures all threads are terminated properly, even in case of application errors.
- Exception Handling: Prevents task exceptions from crashing the thread pool by logging errors and continuing execution.
This class is designed to be used statically, offering centralized methods to manage threads and tasks.
Submits a task for asynchronous execution.
-
Parameters:
task: TheRunnabletask to execute.
-
Description: Uses the fixed-size thread pool to execute tasks without blocking the main thread.
Schedules a task to run periodically at a fixed rate.
-
Parameters:
task: TheRunnabletask to execute.initialDelay: The initial delay before the first execution.period: The time period between successive executions.timeUnit: The unit of time forinitialDelayandperiod.
-
Description: Uses the scheduled thread pool to execute tasks periodically.
Gracefully shuts down all threads.
- Description:
- Stops actively executing tasks.
- Prevents waiting tasks from starting.
- Releases resources associated with the thread pools.
- If threads fail to terminate within 30 seconds, they are forcibly shut down.
Wraps a task to catch and log exceptions during execution.
-
Parameters:
task: TheRunnabletask to wrap.
-
Description: Logs exceptions using
PajamaLoggerand ensures they do not terminate the thread pool.
Call the shutdown() method during application termination to ensure all threads are stopped and resources are released.
ThreadManagerPool is designed to be thread-safe. Internally, it uses ExecutorService instances, which handle synchronization for concurrent task execution.
ThreadManagerPool.runAsync(() -> {
System.out.println("Running asynchronously on thread: " + Thread.currentThread().getName());
});ThreadManagerPool.scheduleAtFixedRate(() -> {
System.out.println("Periodic task running on thread: " + Thread.currentThread().getName());
}, 0, 10, TimeUnit.SECONDS);ThreadManagerPool.shutdown();- Java Concurrency:
ExecutorService,ScheduledExecutorService,Executors,TimeUnit.
- Logging:
PajamaLoggerfor logging exceptions and status messages.
- Default Thread Pool Size: The fixed-size thread pool size is determined by the number of available CPU cores.
- Best Practices: Always call
shutdown()during application termination to avoid resource leaks or orphaned threads.