I am running below program, where Main thread finishes 1st, before calling the get method of the child callable thread.
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newFixedThreadPool(1);
Future<String> f = exec.submit(new TThread());
Thread.sleep(10000);
System.out.println("Main Thread "+System.currentTimeMillis());
String s = (String) f.get();
System.out.println(s);
exec.shutdown();
}
}
class TThread implements Callable<String>{
@Override
public String call() throws Exception{
Thread.sleep(3000);
System.out.println("TThread Thread "+System.currentTimeMillis());
return "something";
}
}
The output is
TThread Thread 1497248667516
Main Thread 1497248674515
something
My expectation was get() might return null, because TThread thread was completed much earlier than to get() call. Does this mean that Java maintains the result from callable irrespective of the caller is calling the get() or not. Also can somebody please explain, how does Java implements such future task.
no, get will return only the possible values returned by the
callmethod in theTThreadclass, in your case "Something", the option left is that the call method gets interrupted, then there is no return at all since the exception propagates in the stack up to theexecutor.submit()invocation.Your micro-benchmark in Java is not working as it should...