Why Thread.currentThread().interrupt() Didn't Work
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.
How To Stop Background Tasks
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.
- First you will have to create something like a SpringBoot service. Which is a singleton class that gets injected into all of the classes that execute your rest endpoints. The service would be a background task tracker, which keeps a mapping from task ID to a flag indicating whether the task should be terminated.
- Next you would have to create a rest endpoint to terminate a background task. The rest endpoint should take the task ID to terminate as a query param or path param.
- When the endpoint executes you can call a terminate method on the background task tracker which will flip the flag indicating that the task should be terminated. Note: Your background task may have finished before you actually terminate it so your code should handle this corner case.
- When you launch your background task you should give it a reference to your background task tracker.
- The very first thing your background task should do is create a unique task ID. You can start with using
UUID.randomUUID()
.
- After creating the task ID give it to your background task tracker.
- Print the task ID in the logs for your background task.
- The background task can proceed to do its work, but it should periodically check the background task tracker if it has been cancelled. If not continue processing, if yes close any resources used and return.
- Before your background task exits, you should remove it from the background task tracker in order to avoid a memory leak.
Important Notes
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