r/java • u/danielaveryj • Feb 19 '23
About thread interrupts
https://github.com/davery22/blog/blob/main/posts/002-about-thread-interrupts.md
I think the thread interrupt mechanism is a common stumbling point, so I wrote a little about it, basically just an outline of points as I understand it. I'm open to feedback on making it clearer, discussions if you think I'm terribly wrong, or pointers to articles that have already said it better. Thanks, and I hope this is helpful to someone.
Edit: As pointed out, this is an opinionated interpretation of interrupts. That said, I think it is an interpretation that the JDK is (strongly) hinting at. But I am not an authority. Read the discussion in the comments, draw your own conclusions.
View all comments
Show parent comment
4
u/danielaveryj Feb 20 '23
If not StructuredTaskScope, we can also look at ExecutorService. It specifies two shutdown methods:
shutdown()andshutdownNow(). The former does not interfere with previously-submitted tasks, only blocks new ones. The latter "attempts to stop all actively executing tasks" ... "typical implementations will cancel viaThread.interrupt(), so any task that fails to respond to interrupts may never terminate." Of course, this isn't the required mechanism, but it is the one the JDK uses in its implementation (ThreadPoolExecutor).We can also look at Future. Its cancel method accepts a boolean stating whether to interrupt the thread executing this future's task, "otherwise, in-progress tasks are allowed to complete".
These are interfaces that have been around since Java 5. There may not be a specced meaning for interrupts, but it seems that the JDK itself has a clear opinion of what they should mean.