I have a REST application with about 30 endpoints. In addition to these the user can submit a background task to be processed that takes 20-60 minutes. Sometimes its obvious that a submitted request will never finish from the logs, however, the only thing I can do is redeploy the same version of the code.
I want to have the ability to kill the process similar to how I can with mySQL via
'Show Process List' -> 'Kill <ProcessId>'.
I tried to implement with Thread.currentThread().interrupt(), but that didn't really do anything. I am using CompletionService and multi-threading numerous times throughout the application to expedite the processes.
My goal is that I should be able to call this API to return the application to the state that it is in when no processes are running. I checked this post, but it seems like everyone is warning against it.
How to find and stop all currently running threads?
Can this be done?
Thread.currentThread()
returns the the Thread object for the current thread you are running in, so if you call this outside of your background task thread, it will not return a reference to your background thread. If you want a reference to your background thread you will have to keep track of it yourself.
thread.interrupt()
sets an interrupt flag on your thread. But if your thread never explicitly checks the interrupt flag, it doesn't do anything. You will have to periodically check the interrupt flag within your background task and then take appropriate action.
if (Thread.currentThread().isInterrupted()) {
finishWork(); // Close any resources used.
return;
}
For your use case I would actually discourage using interrupt() on your background task, especially if you are using a Threadpool. Specifically if you are using a Threadpool, the same thread could be reused to run multiple background tasks. Because the thread is reused it is possible to accidentally interrupt a background task you never intended to.
This will take a fair amount of work of work to do, but it is doable. Below I describe a very rudimentary implementation that will be sufficient for your use case.
UUID.randomUUID()
. Before implementing this be sure to read up on how to properly synchronize communication between threads in java. This is a good resource https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
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.