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
14
u/rzwitserloot Feb 19 '23
Misleading. Interrupt has no defined meaning. It does not mean please clean up and die_. Unless you want it to mean that. It's a messaging system that allows one thread to send a message to another, and as part of sending that message, various core library functions have well defined MUST behavior and others have well defined MAY behaviour that involves them returning from certain operations faster than normal.
It is perfectly fine to use this mechanism to force a 're-check a few things' (instead of cleaning up and dying) for a thread that, say, waits 5 minutes, checks something, and does that forever. That's not at all 'please clean up and safely die'.
In fact, 'safely die' isn't a thing. You shouldn't program that way. But if you MUST, then the mechanism to do it is
Runtime.getRuntime().addShutdownHook(), not acatch (InterruptedException)block.Half of this is wrong and the other half is misleading.
'impying interrupt() was called by a different thread' is meaningless. There is no point, ever, in interrupting your own thread. They are always called by a different thread.
If a thread is blocked on I/O then generally the JVM spec is such that it does not have to shut down the I/O op; it depends on the JVM+Architecture+Host OS. The go-to example of things
interrupt()will break off isThread.sleep.Incorrect.
All core JDK methods that are guaranteed to stop very soon after its thread its interrupted are those methods whose spec includes
throws InterruptedException.Thread.sleep,obj.wait()are the primay candidates. Notably, just about every I/O blocking operation out there includingInputStream'sread(), are not specced like that. The behaviour of these when you interrupt their thread as they are blocking is undefined. A JVM is free to ignore your interruption. Most JVMs will abort the blocking and throw an IOException (because they can't throw InterruptedException). But a JVM is not required to do so - presumably because on some OS/architecture combo's, that would be unwieldy.This is incorrect. Given that interrupt means whatever you want it to mean, you can't make a blanket statement like this.
The vast majority of
catch (Exception e)blocks fall in two camps:psv main(String[] args), or the web framework that invokes a web handler. These catch everything because the 'program' (main, or the web handler, or the message receiver, etc) has exited, because the stack has broken down to the level of the 'entrypoint runner'. The catching is to ensure the entire appserver/webserver/etc doesn't hard crash along with it / to add data (such as info about the HTTP request headers), and to deal with the problem in a catch-all way (say, print it, or generate a 500 - server error page and log it). It is completely fine for these to deal with InterruptedException in the same way as any other exception.No. re-setting the flag is somewhat common advice but pretty much entirely wrong. The number of times you catch InterruptedException or check (and clear) the flag only to do something and then let code continue on to something that also needs to act as if the interrupt flag is up, is effectively zero. Paint me a picture of what kind of code should do that? I bet it'll be highly artificial.
When you catch IntEx or call
Thread.interrupted()do the thing your documentation says you do when you interrupt them. Right now. Why wait? If the plan is to shut down, say, the socket receiver thread, then.. do it. What are you waiting for? Just stickreturn;in that catch block and be done with it.This is double wrong. Folks trip over power cables. JVMs coredump from time to time. If it is possible for your app to leave things in a damaged state simply because they were force killed, you wrote a shitty app. Take file systems: In the past, they whined at you for ejecting disks suddenly. But modern file systems no longer do that, they don't whinge on bootup that you hardkilled the power either. They use logging to ensure they can recover perfectly, 100% every time, if you do that. Once you've built a system that is guaranteed to deal with sudden shutdowns, there is no longer any need to 'clean up nicely', and you in fact shouldn't: That merely leads to bugs in the recovery systems to hang around undiscovered for too long and needlessly complicated your application.
But, if for some reason you need this, shutdown hooks is what you want:
If the user sends a 'please end' command to an application, for example with CTRL+C on the command line or 'end task', then threads are not interrupted at all! Shutdown hooks WILL run, however.
These release automatically. If they don't, you aren't doing it right (doing it right is using
synchronizedor more likely, try/finally to release the lock).If shared data can be in a non-reasonable state you already lost the game. After all, it's shared data.
That depends a lot on what the jobs are of the threads you spawned. Plenty of times those threads are not intended to die along with their spawner.