While I was studying ExecutorService , I came across a Future.get() method that takes a timeout .
Java document of this method says
Waits, if necessary, for no more than the specified time to complete the calculation, and then retrieves its result, if available.
Parameters:
latency maximum latency
unit timeout argument time unit
According to my understanding, we callable timeout on callable , we send it to ExecutorService , so my callable will interrupt after the specified time (timeout) has passed
But according to the code below, longMethod() seems to work outside of the timeout (2 seconds), and I'm really confused, realizing this. Can someone point me in the right way?
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Timeout implements Callable<String> { public void longMethod() { for(int i=0; i< Integer.MAX_VALUE; i++) { System.out.println("a"); } } @Override public String call() throws Exception { longMethod(); return "done"; } public static void main(String[] args) { ExecutorService service = Executors.newSingleThreadExecutor(); try { service.submit(new Timeout()).get(2, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } }
source share