Thursday September 21, 2006
ThreadGroup added to the fun with Sun Fire T1000 The program in the previous blog had limitations with the number of threads argument. Giving a large number ( not much, even something like 10000 ) was resulting in program running out of memory as it had to spawn off so many Thread objects at a time. So I thought let me add some thread pooling. The need was not to have a sophisticated and accurate pooling mechanism but a soft control limit that would prevent the program running out of memory. I felt the java class ThreadGroup was just right for that.
This is how the class looks like now:
public class TestCPU implements Runnable {
static int threads,computes,threadLimit;
static boolean io;
static boolean threading;
public static void main (String args[]) {
TestCPU t = new TestCPU();
try {
threads = (new Integer(args[0])).intValue();
computes = (new Integer(args[1])).intValue();
if ( args[2].equals("Y") ) io = true;
if ( args[3].equals("Y") ) threading = true;
threadLimit = (new Integer(args[4])).intValue();
} catch (Exception nfe) {
// either NumberFormat or ArrayIndexOutOfBounds
System.err.println("Using defaults");
threads=100;
computes=100;
io = false;
threading = false;
threadLimit = 100;
}
System.out.println("Threads: " + threads + " Computes: " + computes );
System.out.println("IO: " + io );
System.out.println("Threading: " + threading);
System.out.println("Thread Pool Size: " + threadLimit);
ThreadGroup pool = new ThreadGroup("pool");
for (int i=0;i<threads;i++) {
if ( threading ) {
if ( pool.activeCount() < (threadLimit) ) {
(new Thread(pool, t)).start();
} else {
--i;
}
} else {
compute();
}
}
System.out.println("done !");
}
public void run() {
compute();
}
static void compute() {
int load;
for (int j=1; j<computes;j++)
for (int k=1; k<computes;k++) {
// do some computing
load = threads + computes;
if ( io ) System.out.println("Load: " + load);
}
}
}
