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.
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.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.
The only way beyond checking the isInterrupted flag is to kill the thread, control the current state and reconcile it somehow. You can obviously encapsulate this inside a class that makes it appear as the isInterrupted flag has been checked.
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