ThreadPool

ThreadPool

 

As we know, dividing tasks into subtasks and execute them via multiple threads can increase throughput and task execution performance. But we should not forget there is a cost associated with thread lifecycle. Thread creations and teardown are not free. So, we are not supposed to create a new thread in the system for every request.

 

We can create a pool of a limited number of worker threads which can execute the task as and when tasks available.  So, instead of creating new thread for every task, we can pass our task to the thread pool if thread pool has any idle thread then it allows to the thread to grab the task and execute but if thread pool doesn’t have any idle thread then it enqueues the task and assign the task to the thread when it becomes available.

 

To create a threadPool we need to follow below simple steps

  1. Create the desired number of threads and run them
  2. we need to provide a BlockingQueue for holding the tasks and share with the created threads.
  3. If BlockingQueue has the task available then one of the thread deQueue the task from the BlockingQueue else BlockingQueue blocks the threads until any task becomes available.
  4. Implement shutDown() method which allow executing only already submitted tasks and won’t accept any new task.
  5. Implement shutDownNow() method which cancel all the tasks that are submitted but execution have not started.

 
Let’s implement the ThreadPool



package com.diaryreaders.multithreading;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* @author Gaurav Gupta
*
*/
public class SystemThreadPool {
final BlockingQueue taskGroup;
final List threadGroup;
private volatile boolean isStopped = false;
public SystemThreadPool(int numberOfThreads, int tasks) {
taskGroup = new ArrayBlockingQueue(tasks);
threadGroup = new ArrayList(numberOfThreads);
while (numberOfThreads-- > 0) {
SystemThread thread = new SystemThread(taskGroup);
threadGroup.add(thread);
thread.start();
}
}
public void execute(Runnable task) {
try {
if (!isStopped()) {
taskGroup.put(task);
} else {
throw new InterruptedException();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @return
*/
private boolean isStopped() {
return isStopped;
}
public synchronized void shutDown() {
isStopped = true;
while (!taskGroup.isEmpty()) {
}
if (taskGroup.isEmpty())
for (SystemThread thread : threadGroup) {
thread.threadStop();
}
}
public synchronized void shutDownNow() {
isStopped = true;
for (SystemThread thread : threadGroup) {
thread.threadStop();
}
}
}
class SystemThread extends Thread {
private static volatile boolean isStopped = false;
BlockingQueue taskGroup;
public SystemThread(BlockingQueue taskGroup) {
this.taskGroup = taskGroup;
}
@Override
public void run() {
while (!isStopped())
try {
Runnable task = taskGroup.take();
task.run();
} catch (InterruptedException e) {
}
}
public synchronized void threadStop() {
isStopped = true;
this.interrupt();
}
/**
* @return
*/
private synchronized boolean isStopped() {
return isStopped;
}
}


 
Test Execution: Execute all the submitted task and Shutdown the service



public class ThreadPoolTest {
public static void main(String[] args) {
SystemThreadPool threadPool = new SystemThreadPool(5, 10);
for (int i = 0; i < 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is getting executed.");
}
});
}
threadPool.shutDown();
}
}
Output:



 
Test Execution: Execute all the running task only and Shutdown the service. It may not execute the all submitted task



public class ThreadPoolTest {
public static void main(String[] args) {
SystemThreadPool threadPool = new SystemThreadPool(5, 10);
for (int i = 0; i < 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is getting executed.");
}
});
}
threadPool.shutDownNow();
}
}
Output:



 
Test Execution: Trying to submit the task after calling Shutdown Service. It will throw InterruptedException



public class ThreadPoolTest {
public static void main(String[] args) {
Runnable task2 = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is getting executed");
}
};
SystemThreadPool threadPool = new SystemThreadPool(5, 10);
for (int i = 0; i < 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is getting executed.");
}
});
}
threadPool.shutDown();
threadPool.execute(task2);
}
}
Output:



 

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON