| 1 21 package org.jsmtpd.generic.threadpool; 22 23 import java.util.Iterator ; 24 import java.util.LinkedList ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 51 public class GenericThreadPool implements ThreadPool { 52 private Log log = LogFactory.getLog(GenericThreadPool.class); 53 private LinkedList <ThreadWorker> threads = new LinkedList <ThreadWorker>(); 54 55 63 public GenericThreadPool(int numThreads, String threadClassName,String displayThreadName) throws InstantiationException , IllegalAccessException , ClassNotFoundException { 64 ThreadWorker tmp; 65 IThreadedClass cls; 66 log.debug("Starting a fixed pool of "+numThreads+" threads"); 67 for (int i = 0; i < numThreads; i++) { 68 tmp = new ThreadWorker(); 69 cls = (IThreadedClass) Class.forName(threadClassName).newInstance(); 70 tmp.setWorker(cls); 71 tmp.setName(displayThreadName+"#"+tmp.getId()); 72 tmp.start(); 73 while (!tmp.isFree()) { 74 Thread.yield(); 76 log.debug("Thread "+tmp.getName()+" ready"); 77 } 78 threads.add(tmp); 79 } 80 } 81 82 86 public void gracefullShutdown() { 87 log.debug("Gracefull shutdown ..."); 88 ThreadWorker tmp; 89 for (int i = 0; i < threads.size(); i++) { 90 tmp = (ThreadWorker) threads.get(i); 91 tmp.gracefullShutdown(); 92 } 93 } 94 95 99 public void forceShutdown() { 100 log.debug("Forcing shutdown ..."); 101 ThreadWorker tmp; 102 for (int i = 0; i < threads.size(); i++) { 103 tmp = (ThreadWorker) threads.get(i); 104 tmp.forceShutdown(); 105 } 106 } 107 108 112 public synchronized boolean hasFreeThread() { 113 for (Iterator iter = threads.iterator(); iter.hasNext();) { 114 ThreadWorker element = (ThreadWorker) iter.next(); 115 if (element.isFree()) 116 return true; 117 } 118 return false; 119 } 120 121 124 public synchronized int countFreeThread() { 125 int count = 0; 126 for (Iterator iter = threads.iterator(); iter.hasNext();) { 127 ThreadWorker element = (ThreadWorker) iter.next(); 128 if (element.isFree()) 129 count++; 130 } 131 return count; 132 } 133 134 139 public synchronized void assignFreeThread(Object obj) throws BusyThreadPoolException { 140 int i = 0; 141 for (Iterator iter = threads.iterator(); iter.hasNext();) { 142 ThreadWorker element = (ThreadWorker) iter.next(); 143 if (element.isFree()) { 144 log.debug("Worker "+element.getName()+" is free, assigning job"); 145 element.setParam(obj); 146 element.wake(); 147 return; 148 } 149 i++; 150 } 151 log.warn("Thread pool exhausted !"); 152 throw new BusyThreadPoolException(); 153 } 154 155 } | Popular Tags |