Implementing a thread pool using a Singleton class in Java

Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 07:51:21 Viewed : 73

Implementing a thread pool using a Singleton class in Java:

Here is an example of implementing a thread pool using a Singleton class in Java:

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolManager { private static ThreadPoolManager instance; private ExecutorService executorService; private ThreadPoolManager() { // Initialize the thread pool executorService = Executors.newFixedThreadPool(10); } public static synchronized ThreadPoolManager getInstance() { if (instance == null) { instance = new ThreadPoolManager(); } return instance; } public void executeTask(Runnable task) { executorService.execute(task); } public void shutdown() { executorService.shutdown(); } }

In this example, the ThreadPoolManager class is implemented as a Singleton using a private constructor and a static getInstance() method.

The ThreadPoolManager class utilizes the ExecutorService from the java.util.concurrent package to create and manage a thread pool. In the constructor, we initialize the executorService with a fixed thread pool of size 10.

The executeTask() method allows you to submit a Runnable task to the thread pool for execution. The shutdown() method is used to gracefully shut down the thread pool when it is no longer needed.

To use the ThreadPoolManager class, you can retrieve the singleton instance using ThreadPoolManager.getInstance() and then execute tasks using the executeTask() method:

ThreadPoolManager threadPoolManager = ThreadPoolManager.getInstance(); // Example task Runnable task = () -> { // Perform some task }; // Submit tasks to the thread pool threadPoolManager.executeTask(task); // Shutdown the thread pool when finished threadPoolManager.shutdown();

Please note that this is a basic example to illustrate the Singleton pattern and thread pool management. In real-world scenarios, you may need to handle task dependencies, monitor task execution, and handle exceptions and retries appropriately based on your specific requirements. Additionally, consider using more advanced thread pool implementations such as ThreadPoolExecutor for fine-grained control over thread pool parameters.

Related Articles

Leave a Comment: