2

I have this frustrating issue: I am trying to see if TimeoutException is thrown in below code, but that doesn't happen ever. It always prints the current time 5 times and finishes.

class MyTask1 implements Callable<Void> {  

    public Void call() throws Exception {  
        for (int i=0; i < 5; i++) {
            System.out.println(new java.util.Date());
            Thread.sleep(1000);
        }
        return null;
    }  
}

public class Timeout {
    public static void main(String[] args) throws Exception {
        FutureTask<Void> futureTask = new FutureTask<Void>(new MyTask1());
        futureTask.run();
        try {
            futureTask.get(1000, TimeUnit.MILLISECONDS); // Check if FutureTask completed in the given time
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            futureTask.cancel(true);
            e.printStackTrace();
        }   
    }
}

I am using Thread.sleep(1000) so that call() method takes at least 5 seconds (as it is done 5 times using a for loop). And I am calling get() method by setting timeout value 1 second.

But why doesn't it throw TimeoutException?

This could be a possible duplicate of How do I get FutureTask to return after TimeoutException?

But appriciate if someone can help as this is really frustrating. Or I didn't understand how to use the FutureTask to handle the timeout?

Community
  • 1
  • 1
ParagJ
  • 1,566
  • 10
  • 38
  • 56

1 Answers1

6

You need to run the FutureTask on a separate thread (using, e.g. an Executor). you are currently running it in the same thread, so the get() call doesn't happen until the run() has already completed.

UPDATE:

If you need help with threading in java, there is a fantastic tutorial in the oracle docs.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • Can you please guide me with an example how to fix this using Executor? Sorry, but I am new to java.util.concurrent package. – ParagJ Jan 03 '13 at 13:20
  • 1
    Thanks a lot for info. I ran it using an Executor and it worked very well. Thank you. – ParagJ Jan 03 '13 at 13:36