Sunday, September 5, 2010

Java 5.0 Multithreading feature - Callable and Future

One of the very important feature of Java 5.0 is Callable Interface and Future.
The problem with Runnable interface or Thread class in multithreading was you can return any value from the thread.
But this drawback was removed in Java 5.0 with Callable Interface and Future.
In the code below, Callable<Interger> in CallableExample, the thread will return 'Integer' and this Integer value can be retrieved using Future object as shown in CallableExampleTest.

1. Callable Implementation:
----->

import java.util.concurrent.Callable;

/**
*
* @author vinitpatwa
*/
public class CallableExample implements Callable<Integer> {

private String word;

public CallableExample(String word) {

this.word = word;
}

public Integer call() {

return getWord().length();

}

public String getWord() {
return word;
}
}

<-----

2. Testing the Callable implementation
----->
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
*
* @author vinitpatwa
*/
public class CallableExampleTest {

public static void main(String args[]) throws Exception{

ExecutorService pool=Executors.newFixedThreadPool(1);
List<Future<Integer>> set=new LinkedList<Future<Integer>>();
String[] strArray={"Texas", "California", "Ohio"};
for(String word:strArray){

Callable cal=new CallableExample(word);
Future<Integer> future=pool.submit(cal);
set.add(future);

}

for(Future<Integer> future:set){
System.out.println("Length of word is : "+future.get());
}
}
}

<-----

No comments: