1 package net.sf.crispy.concurrent; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import net.sf.crispy.InvocationException; 7 8 /** 9 * This class create and controlled all Threads. 10 * 11 * @author Linke 12 * @since Verion 1.0 13 * 14 */ 15 public class ThreadController { 16 17 private int maxThreads = 0; 18 private int threadCounter = 0; 19 private final List pool = new ArrayList(); 20 private ThreadWorker singleton = new ThreadWorker(this); 21 22 23 public void setMaxThreads(int pvMaxThreads) { 24 maxThreads = pvMaxThreads; 25 } 26 public int getMaxThreads() { 27 return maxThreads; 28 } 29 30 /** 31 * Get a new <code>ThreadWorker (Thread)</code> or from pool. 32 * 33 * @return ThreadWorker - Thread 34 */ 35 public synchronized ThreadWorker getThreadWorker() { 36 if (getMaxThreads() > 0 && threadCounter == getMaxThreads()) { 37 throw new InvocationException("Maximum number of concurrent Threads exceeded: " + getMaxThreads() + ". A asynchrone invocation is not possible."); 38 } 39 40 ++threadCounter; 41 if (maxThreads == 0) { 42 return singleton; 43 } 44 if (pool.size() == 0) { 45 return new ThreadWorker(this); 46 } else { 47 return (ThreadWorker) pool.remove(pool.size() - 1); 48 } 49 } 50 51 /** 52 * Release <code>ThreadWorker (Thread)</code> 53 * @param pvThreadWorker the Thread 54 */ 55 public synchronized void releasThreadWorker(ThreadWorker pvThreadWorker) { 56 --threadCounter; 57 if ((pvThreadWorker != singleton) && (pool.size() < maxThreads)) { 58 pool.add(pvThreadWorker); 59 } 60 } 61 62 63 /** 64 * Returns the number of currently running Threads. 65 * @return Current number of Threads. 66 */ 67 public synchronized int getCurrentRequests() { 68 return threadCounter; 69 } 70 }