Using threads and collecting responses

Hello,

I am doing multiple requests to diferent web services from diferent providers. I want to do the requests simultaneously and I think the best way is using threads. I am thinking to create a main class that creates a thread instance for every request (max 5) and then wait for the responses with a timeout. What is best way to implement this? Is there any standard or typical strategy? Different points to consider are:

- time out, the main class can't wait for ever the threads to end.

- how every thread passes the response from de web service to the main class.

Thanks in advance.

[621 byte] By [faliscoa] at [2007-11-27 9:52:24]
# 1

Hi,

best way to do this may be using an executor service. I cant describe this in detail here..basicly you have to create a executor

ExecutorService executor = Executors.newCachedThreadPool();

then you create so called "Callables" which are like Runnables, but return a result. There you implement your thread functionality in the "call" method.

public class testCallable implements Callable{

public Object call() throws Exception {

...}

}

in your controlling class you add these to your executor service and assign the results to a Future (which is a nonblocking operation).

// make a new Thread for each resouce

Future[] futures = new Future[5];

for (int i = 0; i < 5; i++) {

futures[i] = executor.submit(new testCallable());

}

then you retrive the result. You can assign a timeout there.

try {

long timeoutTime = System.currentTimeMillis() + timeout;

for (int i = 0; i < futures.length; i++) {

long remainingTime = Math.max(0, timeoutTime

- System.currentTimeMillis());

try {

Result result = (Result) futures[i].get(

remainingTime, TimeUnit.MILLISECONDS);

}

....

}

}

look at

http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

for details

Greetings

Brash

Brasha at 2007-7-13 0:21:28 > top of Java-index,Core,Core APIs...