3 ms·
What, in your opinion, would be a better mechanism for interrupting threads in Java (aside from just making it an unchecked exception)? Something like Erlang,
by mac01021 6y ago
What, in your opinion, would be a better mechanism for interrupting threads in Java (aside from just making it an unchecked exception)?
Something like Erlang, where any process will just die upon being sent the exit message, whether it's blocked on IO or receive or busy in the CPU, would definitely be simpler and easier to reason about. But that capability carries a runtime cost.
Go's mechanism is also arguably simpler, in which goroutines are not first class objects and if you want to be able to interrupt one then you have to write ad hoc logic using a channel that you provide specifically for the purpose. But in 99.9% of cases, I think Java's more complicated mechanism with first class threads is more convenient.
I would make it an unchecked exception, though. And I wish the old java.io.Socket operations and similar methods would throw InterruptedException.
- hodgesrm 6y agoThis is a really hard problem. If you use exceptions at any level they have to be generated consistently, or the solution will be what we have now. Because that's the other thing--you can't guarantee InterruptedException will even be delivered to a thread. An underlying library can just eat it or the thread could be waiting on a socket [1], etc. This kind of behavior the bane of correctness or even getting operations like clean server shutdown to work at all in some cases. So I think this really needs to be something like CSP that's built into the language in a way that makes the behavior consistent in all cases even if it introduces coding patterns that have other costs. Java _did_ get object locking and data visibility right by building in simple primitives like the synchronized keyword into the language. You can create deadlocks but the behavior is clean enough it's not hard to program around them. I would also be fine with just dying as long as there is a way to clean up shared data structures. However, that can't be manual because it's just about impossible to ensure that such cleanups are correct. Databases use transactions to get around that problem. [1] https://stackoverflow.com/questions/1024482/stop-interrupt-threads-blocked-on-waiting-input-from-socket https://stackoverflow.com/questions/1024482/stop-interrupt-t...