Your own Thread Pool

"Create your own thread pool" - A typical interview question, asked to check if you have a basic understanding of Thread Pool, Runnable, and the disadvantages of creating a new Thread for each Task.

ThreadPool is made up of a number of threads, identified by the core thread pool size. Once you start the ThreadPool, all the threads start running, waiting for the task. Each task or Runnable that you submit to the ThreadPool is executed by the existing threads of the ThreadPool.

Creating a thread is expensive, so it is advisable to have a ThreadPool which manages the tasks.

Here is a program which creates its own ThreadPool - MyThreadPool.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool {

 private int corePoolSize;

 private MyThread tPool[];

 private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1024);

 public MyThreadPool(int corePoolSize) {
  this.corePoolSize = corePoolSize;
  tPool = new MyThread[corePoolSize];
  for (int i = 0; i < corePoolSize; i++) {
   tPool[i] = new MyThread();
  }
  for (MyThread t : tPool) {
   t.start();
  }

 }

 public void addTask(Runnable r) throws InterruptedException {
  queue.put(r);
 }

 public void stopAll() {
  for (MyThread t : tPool) {
   t.stopMe();
  }
 }

 public int getCorePoolSize() {
  return corePoolSize;
 }

 private class MyThread extends Thread {

  private boolean isStopped = false;

  public void run() {
   while (!isStopped) {
    try {
     Runnable r = queue.take();
     r.run();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }

  public void stopMe() {
   isStopped = true;
   this.interrupt();
  }
 }
}

public class MyThreadPoolTest {

 public static void main(String[] args) throws InterruptedException {
  MyThreadPool pool = new MyThreadPool(10);
  for (int i = 0; i < 100; i++) {
   final int id = i;
   pool.addTask(() -> {
    System.out.println("Id : " + id);
   });
  }
  Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() {
    pool.stopAll();
   }
  });

 }
}

Comments

Popular posts from this blog

Writing your own ejabberd Module

npm ECONNREFUSED error

Conditional Flow - Spring Batch Part 6