1 3 package org.jgroups.util; 4 5 6 import org.apache.commons.logging.Log; 7 import org.apache.commons.logging.LogFactory; 8 9 10 20 public class ThreadPool { 21 int MAX_NUM=255; 22 int current_index=0; ReusableThread[] pool=null; 24 boolean[] available_threads=null; 25 protected static final Log log=LogFactory.getLog(ThreadPool.class); 26 27 28 29 public ThreadPool(int max_num) { 30 MAX_NUM=max_num; 31 pool=new ReusableThread[MAX_NUM]; 32 available_threads=new boolean[MAX_NUM]; 33 for(int i=0; i < pool.length; i++) { 34 pool[i]=null; 35 available_threads[i]=true; 36 } 37 if(log.isDebugEnabled()) log.debug("created a pool of " + MAX_NUM + " threads"); 38 } 39 40 41 public ReusableThread getThread() { 42 ReusableThread retval=null, tmp; 43 44 synchronized(pool) { 45 for(int i=0; i < current_index; i++) { 47 tmp=pool[i]; 48 if(tmp.available()) { 49 return tmp; 50 } 51 } 52 53 if(current_index >= MAX_NUM) { 55 if(log.isErrorEnabled()) log.error("could not create new thread because " + 56 "pool's max size reached (" + MAX_NUM + ") !"); 57 return null; 58 } 59 else { 60 retval=new ReusableThread(); 61 pool[current_index++]=retval; 62 return retval; 63 } 64 } 65 66 } 67 68 69 public void destroy() { 70 deletePool(); 71 } 72 73 74 public String toString() { 75 StringBuffer ret=new StringBuffer (); 76 77 synchronized(pool) { 78 ret.append("ThreadPool: capacity=" + pool.length + ", index=" + current_index + '\n'); 79 ret.append("Threads are:\n"); 80 for(int i=0; i < current_index; i++) 81 ret.append("[" + i + ": " + pool[i] + "]\n"); 82 } 83 return ret.toString(); 84 } 85 86 87 void deletePool() { 88 ReusableThread t; 89 synchronized(pool) { 90 for(int i=0; i < MAX_NUM; i++) { 91 t=pool[i]; 92 if(t != null) { 93 t.stop(); 94 pool[i]=null; 95 } 96 } 97 current_index=0; 98 } 99 } 100 101 102 } 103 | Popular Tags |