Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement synchronous method timeouts in Java?

Tags:

I have an synchronous execution path which needs to either complete or timeout within a given time frame. Let's say I have a class with main() method in which I invoke methods A() which in-turn calls B() and that in-turn calls C() of same or different classes.....all synchronous without using an external resource like database , webservice or file system (where each of them could be timed out independently using a TxManager or respective timeout api's). So it's more like a CPU or memory intensive computation. How do I code for it's timeout in Java ?

I have looked at TimerTask but that more of making the flow async and for scheduling tasks. Any other suggestions ?

like image 857
Smitesh Avatar asked Jun 21 '13 10:06

Smitesh


1 Answers

You should use ExecutorService to do that

ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable() {      public String call() throws Exception {         //do operations you want         return "OK";     } }); try {     System.out.println(future.get(2, TimeUnit.SECONDS)); //timeout is in 2 seconds } catch (TimeoutException e) {     System.err.println("Timeout"); } executor.shutdownNow(); 
like image 161
Tala Avatar answered Oct 20 '22 18:10

Tala