Thread Pool in Java

Β What is Thread Pool ?

Lets understand how we create usually create a thread pool.

Thread Pool in java is a reserved pool of worker threads to which tasks are given to execute or complete.

Threads are created by either implementing the Runnable interface or extending the Thread class. Lets take an example.

ThreadPool Execution

package ThreadPool;

public class Task implements Runnable
{

@Override
public void run() {
System.out.println("Thread Name:"+Thread.currentThread().getName());
}

}


package ThreadPool;

public class TaskImpl 
{
public static void main(String[] args) 
{
Thread t1=new Thread(new Task());
t1.start();

}
}

In this example, there is a main thread which creates new child thread t1 and performs its operation in run method.

Now, if we want to create a 1000 threads then we can do like

public static void main(String[] args) 
{
for(int i=0;i<1000;i++)
{
Thread t1=new Thread(new Task());
t1.start();
}
}

This program will create thousand threads which corresponds to thousands operating system threads from t0 to t999. And creating a thread is itself is quite expensive process which takes a lot of memory in jvm and might turn up into the outofmemory error.

To overcome this problem, there is a concept of thread pool. We will create a fixed number of worker threads that will do its operations submitted. So we will create a pool of threads which will do its task.

Executor Framework in Java

Thread pool are created using the Executor Service framework.

package ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskImpl 
{
public static void main(String[] args) 
{
ExecutorService service=Executors.newFixedThreadPool(10);
for(int i=0;i<1000;i++)
{
service.execute(new Task()); 
}
}
}

ExecutorService is a interface and Executors is a class which has static method newFixedThreadPool. This method takes argument as number of worker thread as 10. These number of threads called as Thread Pool which can be decided on certain parameters.

These 10 threads will be created and will perform the submitted 1000 tasks. The execute method takes the Runnable tasks. We can submit or execute the new tasks using the execute or submit method.

Executor Framework internally uses the BlockingQueue for tasks submission.

ThreadPool Explanation

Ideal Pool Size

Ideal thread pool size depends on the number of threads requirement and number of CPU core available.

If there are 4 cores in the CPU then ideal size of thread pool should beΒ  maximum of 4.

Types of Thread Pool

There are four types of thread pool:

  1. FixedThreadPool
  2. CachedThreadPool
  3. ScheduledThreadPool
  4. SingleThreadedExecutor

Fixed Thread Pool

It creates fixed number of threads in a pool which can be used as worker threads and does the tasks provided. It internally uses the BlockingQueue. All the submitted tasks are stored in the BlockingQueue and executes tasks one by one by the available worker threads.

In below example there will be 10 worker threads inside pool and 100 tasks are given.

package ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskImpl 
{
public static void main(String[] args) 
{
ExecutorService service=Executors.newFixedThreadPool(10);
for(int i=0;i<100;i++)
{
service.execute(new Task()); 
}
}}

CachedThreadPool

Here we do not have fixed size of thread pool. Instead of BlockingQueue it has the synchronous queue which will receive the submitted task and allocate it to the thread.

If thread is idle for 60 secs (ideal time) then that particular thread will be killed and will not be available if it is no longer required and there is no task to submit. And thread pool size will start shrinking.

If the previous submitted task has created a new thread and is busy then new submitted task will create a new thread.

ThreadPool Execution

package ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskImpl 
{
public static void main(String[] args) 
{

ExecutorService service=Executors.newCachedThreadPool();
for(int i=0;i<10;i++)
{
service.execute(new Task()); 
}
}

}

ScheduledThreadPool

This thread pool is used for scheduling the task after certain delay.

It has three important methods i.e. schedule(), scheduleAtFixedRate(), scheduleAtFixedDelay(). First method will schedule a task once the previos is completed.

Second methodΒ scheduleAtFixedRate() will schedule the task after the fixed interval of time whether the previous submitted task is completed or not.

Third method scheduleAtFixedDelay() will schedule the task after the the fixed delay.

Thread Pool in Java, Executor Framework

SingleThreadExecutor

It will create only one thread and will execute the submitted tasks one by one.

package ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskImpl 
{
public static void main(String[] args) 
{

ExecutorService service=Executors.newSingleThreadExecutor();
for(int i=0;i<10;i++)
{
service.execute(new Task()); 
}
}

}

Conclusion

Thread Pool framework is extremely important part of java concurrency and widely used in multithreaded programming. It enables to create a pool of thread which can perform the worker tasks. Several types of thread pool in java gives important multithreading functionality to you.

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

2 Comments

  1. it very well explanation πŸ™‚

Leave a Reply