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 ?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With