Reputation: 1315
I have a simple spring controller, which waits for some actions to be done. Let's say it looks like the following:
@GetMapping("/wait")
public void waitForFinish() throws InterruptedException {
while (!allJobsAreFinished()) {
Thread.sleep(5000);
}
}
Now, for some reason, I want to interrupt this thread in a separate request. For this purpose, I save running thread to a map and in a separate method call .interrupt()
on it:
private Map<String, Thread> runningThreads = new ConcurrentHashMap<>();
@GetMapping("/wait")
public void waitForFinish() throws InterruptedException {
Thread currentThread = Thread.currentThread();
runningThreads.put("testId", currentThread);
//...
runningThreads.remove("testId");
}
@GetMapping("/cancel")
public void cancel() {
runningThreads.get("testId").interrupt();
}
My question is the following: is it a good idea to interrupt threads created by Spring? What can go wrong if I interrupt Spring thread? Or it is better to create ExecutorService
, submit my tasks to it and interrupt them there via Future
?
Upvotes: 1
Views: 2282
Reputation: 6302
Do not interrupt threads that you don't know the consequences.
It could be done for threads that you created, you started, and you know what are the side effects.
Upvotes: 3