Tuesday, August 7, 2007

Thread pool implementation in Java 1.5

Most of the application in J2EE these days require multi threading programming. And i was wondering why has java not provided implementation of Thread pool. And I found one with Java 1.5.

Java 1.5 has introduced a new package java.util.concurrent. That package deals with so many synchronization related things. Read this.

One of them is implementation of Thread pool.

I wanted to implement thread pooling to ping all the machine in the given IP range. I was exploring java.util.concurrent package and found Thread Pool implementation is so easy to use.

This is the code that i had to write and i was done with Thread pool implementation which required at least 2-3 classes to be written with earlier version of Java.

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MultiThreadedPing {

public static void main(String[] args){

String networkAddress = "10.88.68.";
int tpSize = 10;
String ipAddress = null;
ThreadPoolExecutor tpe = new ThreadPoolExecutor(tpSize,tpSize,50000L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue());

for(int i=2;i<20;i++){

ipAddress = networkAddress + String.valueOf(i);
PingThread pt = new PingThread(ipAddress);





class PingThread implements Runnable{

private String ipAddress;

public PingThread(String ipAddress){
this.ipAddress = ipAddress;

public void run(){

String pingResult = "";
String pingCmd = "ping -n 1 -w 100 " + this.ipAddress;

try {

Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
System.out.println("Pinging " + ipAddress);

while ((inputLine = in.readLine()) != null) {

if(inputLine.contains("Reply from".subSequence(0,10))){

System.out.println("Got response from " + ipAddress);
AvailableIps.ipAddresses += this.ipAddress;


else if(inputLine.contains("Request timed out.".subSequence(0,18))){

System.out.println("No response from " + ipAddress);
NotAvailableIps.ipAddresses += this.ipAddress;




catch (IOException e) {





class AvailableIps{ public static String ipAddresses = ""; }

class NotAvailableIps{ public static String ipAddresses = ""; }

So Thread pooling is just understanding a class away now. :-)