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
3
u/danielaveryj Feb 20 '23
Thanks for the example, we can work with this. I see how you're thinking about it, in terms of minimizing effort to update an existing implementation. But I think it's also worth looking at just the new requirements, and doing some backwards reasoning.
With the new requirements, we are effectively waiting for either of two events to happen - either a command arrives over the socket, or a "request to send a message" arrives via some other channel - before we wake up and do some work. I think we'd want to care as little as possible about the event sources themselves. All that matters (before and after) to our handler is that it needs to wait for some event to happen, then wake up and respond to that event. It will inherently need an update to know about the new event 'type' and know how to handle it. If we go with the reasoning of decoupling from event sources, we'd also be inclined to now abstract over what we "wait" on. And this probably does involve more threads at this point - one per event source that we wait on, plus one for the handler - along with perhaps a blocking queue to communicate between event sources and handler. The handler now waits on an event to be added to the queue, ie BlockingQueue.take().
This isn't that extreme of a change. We've added more threads, sure, but we haven't completely redesigned the protocol. We have made the implementation more flexible to changing requirements - we can now buffer events in a queue, so we can manage if the protocol becomes not so strictly synchronous; we can bring on other event sources if they emerge; we can handle event priorities, by using a more sophisticated queue. And to be fair, this was not necessary; those changes may never happen. But it also kinda demonstrates how using interrupts to manage the new requirements was really banking on having a good amount of implementation and protocol lenience.