Reputation: 1731
How would you kill a thread in Java without manually checking Thread.currentThread().isInterrupted()
?
For example, how would you kill a thread like this after a time out:
new Thread(() -> {
Result result = ExternalLibrary.performSomeReallyLongRunningTaskWithNoSideEffects();
System.out.println(result);
}).start();
We cannot modify the external library code to add isInterrupted
checks everywhere
Upvotes: 3
Views: 566
Reputation: 72
For the timeout part, if you're open to using guava, SimpleTimeLimiter
is a good option.
If you're long running thread does frequent IO, it may be as simple as using an interrupt (which for SimpleTimeLimiter
you just need to invoke with amInterruptible=true
), because IO operations will generally check the interrupt flag and throw an InterruptedException
which you'd hope the third party code will propogate or use to terminate the operation.
If you're long running method doesn't check interrupts or ignores them, and modifying it is not an option, you may be stuck with Thread.stop()
, which is deprecated. If the long-running task is sufficiently isolated in it's operation, i.e. doesn't share variables with other running threads, and doesn't open any resources, it may be fine to just do that. But there is no way to be sure. I would definitely just try an interrupt first, it may just work.
Another alternative if the 3rd party code is truly opaque and unmodifiable, is convert it into it's own jar, and invoke it as an external process. That way the process can always be killed in isolation from your application.
In either the case of using Thread.stop()
or a sending a kill signal to a separate process, you can execute these operations in response to the UncheckedTimeoutException
thrown by SimpleTimeLimiter#callWithTimeout(...)
Upvotes: 1