How would you implement a thread pool

Showing Answers 1 - 7 of 7 Answers

Pankaj Dwivedi

  • Jun 16th, 2005
 

public class ThreadPool extends java.lang.Object implements ThreadPoolInt 
 
This class is an generic implementation of a thread pool, which takes the following input 
a) Size of the pool to be constructed 
b) Name of the class which implements Runnable (which has a visible default constructor) 
and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool. 
 
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool 

  Was this answer useful?  Yes

Two ways of implementing your own thread pool.

a. Using the java.util.concurrent.Executors class which contains the static methods
newFixedThreadPool(), newCachedThreadPool() etc for creating thread pool with number of threads.

b. Creating a new thread pool as below.

import java.util.LinkedList;
public class WorkQueue {
     private final PoolWorker[] threads;private final LinkedList queue;
     public WorkQueue(int nThreads) {
          queue = new LinkedList();threads = new PoolWorker[nThreads]; 
          for (int i = 0; i < nThreads; i++) {threads[i] = new PoolWorker();threads[i].start(); 
          }
}
public void execute(Runnable r) {
     synchronized (queue) { 
          queue.addLast(r);queue.notify();
     }
}

private class PoolWorker extends Thread {public void run() {
Runnable r;
while (true) {
     synchronized (queue) { 
          while (queue.isEmpty()) { 
               try { 
                    queue.wait();} catch (InterruptedException ignored) {} 
               } 
               r = (Runnable) queue.removeFirst(); 
          } 

          // If we don't catch RuntimeException, 
          // the pool could leak threads 
          try { 
               r.run(); 
          } catch (RuntimeException e) { 
               // You might want to log something here 
          } 
     }
  }
 }
}

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions