Custom Thread Pool Implementation

Implementing a custom fixed-size thread pool involves creating a class that manages a pool of worker threads and a queue to hold the tasks. Below is a complete implementation that demonstrates how to create a basic fixed-size thread pool in Java:

Custom Fixed-Size Thread Pool Implementation

Here’s how to implement a custom fixed-size thread pool:

  1. Thread Pool Class: Create a class that manages the worker threads and a task queue.
  2. Worker Threads: Each thread will continuously fetch tasks from the queue and execute them.
  3. Task Queue: A blocking queue is used to hold tasks until they can be executed.
  4. Thread Management: Manage thread lifecycle and ensure they shut down gracefully.

Complete Code Example

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class CustomFixedThreadPool {
    private final int numberOfThreads;
    private final WorkerThread[] threads;
    private final BlockingQueue<Runnable> taskQueue;

    public CustomFixedThreadPool(int numberOfThreads) {
        this.numberOfThreads = numberOfThreads;
        this.threads = new WorkerThread[numberOfThreads];
        this.taskQueue = new LinkedBlockingQueue<>();

        for (int i = 0; i < numberOfThreads; i++) {
            threads[i] = new WorkerThread();
            threads[i].start(); // Start each worker thread
        }
    }

    // Method to submit a new task to the pool
    public void submit(Runnable task) {
        try {
            taskQueue.put(task); // Add task to the queue
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Failed to submit task: " + e.getMessage());
        }
    }

    // Method to shut down the thread pool gracefully
    public void shutdown() {
        for (WorkerThread thread : threads) {
            thread.interrupt(); // Interrupt each worker thread to exit
        }
    }

    // Worker thread class
    private class WorkerThread extends Thread {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Runnable task = taskQueue.take(); // Take a task from the queue
                    task.run(); // Execute the task
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // Restore interrupted status
                }
            }
        }
    }

    public static void main(String[] args) {
        CustomFixedThreadPool threadPool = new CustomFixedThreadPool(3); // Create a pool with 3 threads

        // Submit multiple tasks
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            threadPool.submit(() -> {
                System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                System.out.println("Task " + taskId + " has completed.");
            });
        }

        // Shutdown the thread pool after submitting tasks
        threadPool.shutdown();
    }
}

Explanation of the Code:

  1. CustomFixedThreadPool Class:

    • Manages a fixed number of threads (numberOfThreads).
    • Contains a blocking queue (taskQueue) to hold tasks.
  2. WorkerThread Inner Class:

    • Each WorkerThread runs in a loop, taking tasks from the taskQueue and executing them.
    • The thread checks for interruptions to allow graceful shutdown.
  3. submit Method:

    • Allows submission of tasks to the thread pool.
    • Adds tasks to the taskQueue. If interrupted while waiting, it restores the interrupted status.
  4. shutdown Method:

    • Interrupts all worker threads to stop them from waiting for new tasks.
  5. Main Method:

    • Creates an instance of CustomFixedThreadPool with 3 threads.
    • Submits 10 tasks to the thread pool.
    • Shuts down the thread pool after submitting tasks.

Example Output

When you run the above code, the output might look like this:

Task 1 is running on thread Thread-0
Task 2 is running on thread Thread-1
Task 3 is running on thread Thread-2
Task 1 has completed.
Task 4 is running on thread Thread-0
Task 5 is running on thread Thread-1
Task 2 has completed.
Task 3 has completed.
...

Summary

This implementation of a custom fixed-size thread pool demonstrates the basic mechanics of thread management, task queuing, and execution. It is a simple and effective way to manage concurrent tasks in a multi-threaded environment.

Feel free to enhance this implementation by adding features such as:

  • Handling task exceptions.
  • Implementing a method to wait for all tasks to complete.
  • Allowing graceful shutdown with an option to wait for ongoing tasks to finish.

Post a Comment

Previous Post Next Post