I need to time limit a long running function which has zero loops. I run that function using a Callable and call get on the future with a timeout value. AFAIU, future.cancel(true) will set the interrupt flag for the function thread. But until and unless I check and handle Thread.isInterrupted() in longRunningFunction() my code will be unaware that it has to exit and even after shutdownNow() the function will not terminate.
- How to check for interrupted in
longRunningFunction()? The check needs to be prompt i.e if the check is put at specific points then until those points are hit, the thread will not handle the interrupt. - Is there any other graceful way to time limit function?
- Why can't I just kill all threads in executor pool? As per JavaDocs for ExecutorService the pool will never terminate until the threads handle interrupt and terminate themselves.
public class Test {
public void longRunningFunction() {
/*
Long running code without loop
*/
}
public Void call() {
try {
longRunningFunction()
} catch (InterruptedException exception) {
logger.error("{} Error : {}", TAG, exception.getStackTrace().join("\n"))
} catch (Exception exception) {
logger.error("[call]{} Error : {}", TAG, exception.getStackTrace().join("\n"))
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor()
Future<Void> future = executor.submit(new Test())
int timeoutSeconds = 5
println "Setting timeout to " + timeoutSeconds
try {
future.get(timeoutSeconds, TimeUnit.SECONDS)
} catch (TimeoutException e) {
future.cancel(true)
logger.error("Could not finish processing within {} seconds", timeoutSeconds)
} finally {
executor.shutdownNow()
executor.awaitTermination(3, TimeUnit.SECONDS)
logger.error("Shutting down")
}
}
}
Edit
The question linked for marking duplicate suggests that shared variables are the way to go, which is a known fact as mentioned in the question. The question is to how seamlessly check for that boolean flag i.e Thread.isInterrupted.