Runnable JDK 1.0
new Thread( () -> System.out.println("Runnable") ).start()
Callbale Java 5
Callable callable = Executors.callable(Runnable task);
Callable returns Future object
call method can throw checked exception
Future result = exec.submit(aCallable);
Response = result.get();
Callable<String> callable = () -> {
// Perform some computation
Thread.sleep(2000);
return "Return some result";
};
Remember, Future.get() is a blocking method and blocks until execution is finished,
so you should always call this method with a timeout to avoid deadlock or livelock in your application
while(!future.isDone()) {
System.out.println("Task is still not done...");
Thread.sleep(200);
double elapsedTimeInSec = (System.nanoTime() - startTime)/1000000000.0;
if(elapsedTimeInSec > 1) {
future.cancel(true);
}
}
future.get(100,TimeUnit.MILLISECONDS) :
Method waits for the result of the task atmost 100 milliseconds, If the wait time out, then get throws TimeoutException.
( future : future_results){
response= future.get();
}
Keep in mind future.get() will get blocked if its not completed. if future get is in loop , it will not proceed for the next future get call.
If application receives multiple http request thread , it is prone to get all app thread blocked resulting application unresponsive.
No comments:
Post a Comment