I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.
If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.
Now, how do I do this?
You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You'd have to adapt this to your needs.
Make a class MyTask implements Callable<Void>
package testapp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
class MyTask implements Callable<Void> {
private String name;
private long sleepTime;
public MyTask(String name, long sleepTime) {
this.name = name;
this.sleepTime = sleepTime;
}
public Void call() throws Exception {
System.out.println("Starting task " + name);
Thread.sleep(sleepTime);
System.out.println("Finished task " + name);
return null;
}
}
Use this as is done here
public class ExecutorServiceTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Collection<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
tasks.add(new MyTask("Task1", 10000));
tasks.add(new MyTask("Task2", 2000));
System.out.println(new java.util.Date());
List<Future<Void>> taskFutures = service.invokeAll(tasks, 2L, TimeUnit.SECONDS);
for (Future<Void> future : taskFutures) {
System.out.println("Done: " + future.isDone());
System.out.println("Cancelled: " + future.isCancelled());
}
System.out.println(new java.util.Date());
System.out.println("END");
}
}
No comments:
Post a Comment