Interview Questions

How can you implement your own Thread Pool in java?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

51. How can you implement your own Thread Pool in java?

What is ThreadPool?
ThreadPool is a pool of threads which reuses a fixed number of threads to execute tasks.

At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

ThreadPool implementation internally uses LinkedBlockingQueue for adding and removing tasks.

In this post i will be using LinkedBlockingQueue provide by java Api, you can refer this post for implementing ThreadPool using custom LinkedBlockingQueue.

Need/Advantage of ThreadPool?
Instead of creating new thread every time for executing tasks, we can create ThreadPool which reuses a fixed number of threads for executing tasks. As threads are reused, performance of our application improves drastically.

How ThreadPool works?
We will instantiate ThreadPool, in ThreadPool’s constructor nThreads number of threads are created and started.

ThreadPool threadPool=new ThreadPool(2);
Here 2 threads will be created and started in ThreadPool.
Then, threads will enter run() method of ThreadPoolsThread class and will call take() method on taskQueue.
If tasks are available thread will execute task by entering run() method of task (As tasks executed always implements Runnable).

public void run() {
. . .
while (true) {
. . .
Runnable runnable = taskQueue.take();
runnable.run();
. . .
}
. . .
}


When tasks are added?
When execute() method of ThreadPool is called, it internally calls put() method on taskQueue to add tasks.
taskQueue.put(task);

Once tasks are available all waiting threads are notified that task is available.

(Continued on next question...)

Other Interview Questions