For example I have some code block which takes more than 30 seconds to execute but I want to stop that if it takes more than 30 seconds. I am trying with executor.shutdown(), executor.awaitTermination(30, TimeUnit.SECONDS) and executor.shutdownNow(); but i can not understand where I have to write my code block which I want to terminate after a specific time. Please give an perfect example.
-
1You can't do that reliably, so you're going to have to rethink what you're doing. – Kayaman Jan 28 '18 at 18:16
-
Please show your attempt, even if you think it is wrong. It will help to illustrate what you are trying to do. – Andy Turner Jan 28 '18 at 18:17
2 Answers
It is pretty simple: when using threads there is no reliable way to kill that thread ( see here for example).
The only choice: start another JVM in another process - because that you can actually kill. See here for details.
Of course - this is rather not the way to go. A better way would be to implement your long-running-task in a way that regularly checks for "cancel" commands for example.

- 137,827
- 25
- 176
- 248
The way to go with your methods mentioned, you just add your task to the executor
, then in the next line of code put executor.shutdown();
It restricts your executor from taking other tasks and then your actually put executor.awaitTermination(30, TimeUnit.SECONDS)
to set the "timer" to wait for the task to complete during this time
A simple samle code snipet:
ExecutorService taskExecutor = Executors.newFixedThreadPool(1);
taskExecutor.execute(new MyTask());
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
...
}

- 10,294
- 9
- 54
- 89