I am trying to implement timeout for a thread which is invoked asynchronously by executor.
Process flow is like below:
Thread-1: Initiates a task to run on thread-2 using below code and returns immediately without waiting for Future object result
Thread-2: Long process and wil update some store some result in cache at end
Now, the requirement is to kill Thread-2 after some timeout value without blocking Thread-1
code snippet:
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Task> future = executor.submit(new Callable<Task>() {
public Task call() throws Exception {
try{
return new Task();
}catch (Exception e) {
//print stack
}
}
});
Any insight/suggestions to implement this?
See the following answer: https://stackoverflow.com/a/2733370/1299078
But depending on what Thread-2 does, you could let the thread end regularly, ie define a timeout on a http-request or a DB statement or if you have a loop, define an exit condition. this way you may end up with a more proper solution and you are able to properly release resources.
You can't do it using Java's ExecutorService because it doesn't expose any method to timeout and kill/complete/finish the newly spawned thread.
However, if you must do it then you can do it by directly using Thread class, below is high level approach:
t2.interrupt()
, this will basically interrupt the t2 thread. if (Thread.interrupted()) {
) and if it is interrupted then you can do whatever you want to do like - simply return therefore completing/killing/finishing the thread. The basic ExecutorService does not provide a timeout functionality.
You could implement the timeout yourself like described by @hagrawal or you can use guava which has a very nice implementation for what you're asking for here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.