-3

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.

Shahriar
  • 1
  • 1

2 Answers2

0

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

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) {
  ...
}
Rainmaker
  • 10,294
  • 9
  • 54
  • 89