Skip to content

Instantly share code, notes, and snippets.

@pratapaditya1997
Created July 8, 2020 16:19
Show Gist options
  • Save pratapaditya1997/862aa238f032ed574cff572cad22b44f to your computer and use it in GitHub Desktop.
Save pratapaditya1997/862aa238f032ed574cff572cad22b44f to your computer and use it in GitHub Desktop.
Thread pool implementation using our BlockingQueue created earlier
//we are using our own definition of BlockingQueue as created by us in BlockingQueue.java file
public class ThreadPool {
private BlockingQueue<Runnable> taskQueue = null;
private List<PoolThread> threads = new ArrayList<PoolThread>();
private boolean isStopped = false;
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
taskQueue = new BlockingQueue<Runnable>(maxNoOfTasks);
for(int i=0; i<noOfThreads; i++) {
threads.add(new PoolThread(taskQueue));
}
for(PoolThread thread: threads) {
thread.start();
}
}
/*
* to execute task this method is called ThreadPool.execute(Runnable r) with a runnable implementation as parameter
* this runnable is en-queued(added) in the blocking queue, waiting to be de-queued
*/
public synchronized void execute(Runnable task) throws Exception {
if(this.isStopped) throw new IllegalStateException("Thread Pool is stopped");
this.taskQueue.add(task);
}
public synchronized void stop() {
this.isStopped = true;
for(PoolThread thread: threads) {
thread.doStop();
}
}
}
class PoolThread extends Thread {
private BlockingQueue taskQueue = null;
private boolean isStopped = false;
public PoolThread(BlockingQueue queue) {
taskQueue = queue;
}
public void run() {
/*
* after execution, PoolThread loops and tries to de-queue a task again, until it is stopped
*/
while(!isStopped()) {
try {
Runnable runnable = taskQueue.remove();
runnable.run();
} catch (Exception e) {
// log it here
}
}
}
public synchronized void doStop() {
isStopped = true;
this.interrupt(); // break thread out of remove call
}
public synchronized boolean isStopped() {
return isStopped;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment