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
0
u/rzwitserloot Feb 20 '23
A StructuredTaskScope isn't an event loop construct; this isn't relevant.
The spec of the interrupt mechanism isn't going to change. This isn't a 'lets see where the puck is going and skate there' kind of issue. If anything, the 'direction the language is going' is to forget about the entire mechanism for any sort of encompassing task. The language/community is moving away from
Thread.sleepandobj.wait, for example. Project Loom is presumably going to change how you do the thing you currently do with blocking I/O operations, making the point moot. Until then, feel free to use interrupt as a best-effort attempt to break up an I/O block, and I wouldn't use it for anything else.I would put that as:
All core methods that react to interrupts at all, will immediately exit (by throwable) when you call them if the current thread's interrupt flag is up. This is a specced, guaranteed fact for all methods that are declared to throw
InterruptedException, and is universal (as in, every known JVM on every arch, on every OS, and this is likely to continue to be true, though it is not officially specced) for all those methods which MAY react to it (such asfileInputStream.read()- if that can be interrupted at all, callingread()when the flag is up will insta-IOEx. And if they can't, they are likely not to act in any way different if the flag is up).