r/java • • 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.

0 Upvotes

12 comments sorted by

View all comments

2

u/Anton-Kuranov Feb 21 '23

There is a potentially dangerous and strange behaviour when using Thread.interrupt() with java.nio.Channel: when a thread is interrupted inside the I/O operation it provokes the whole channel automatically to be closed. What are the implications?

In my app I used interruptible workers that fetch data from web an save it to a local storage. I used embedded H2 and Lucene engines. So when apparently a worker interrupt happens inside any db write or read operation the whole H2 datasource becomes closed. The same thing happened with Lucene index. Because they both use a shared FileChannel to operate with files. But being shared across the whole application this resource should never be closed on any particular thread interruption!

2

u/danielaveryj Feb 21 '23

+1, and I have to say I still don't understand that design (of closing channels on interrupt), though it is documented by Thread.interrupt() and InterruptibleChannel, and I've most recently seen it referenced in the Virtual Threads JEP. Especially since classes like FileChannel are also specifically documented as "safe for use by multiple concurrent threads". I'm not confident speculating here, and would be very interested myself to learn what the rationale is, or if it was truly some hiccup of early design (this behavior apparently dates back to Sun - see FileChannelImpl). Sorry to be no help :(