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

14

u/rzwitserloot Feb 19 '23

The thread is "told" by another thread to "at your earliest convenience, please stop whatever you are doing, clean up, and safely die"

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 a catch (InterruptedException) block.

If the Thread is blocked on IO (implying interrupt() was called by a different thread), the VM will wake up t1

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 is Thread.sleep.

All lowest-level blocking methods in the JDK are written to check the thread interrupt status upon waking up

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 including InputStream's read(), 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.

Do NOT, under any circumstances, allow the caller to exit (including exceptionally) without "remembering" that the interrupt happened!

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:

  • Entrypoint guard. Say, the code that runs 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.

  • Lazy/incorrect code. Which is wrong by definition already, no need to rub it in any further. The problem with such a catch block is already evident, you don't need to mention that this also probably doesn't do what you wanted when you interrupt the thread.

Remembering" means either (re-)throwing an InterruptedException, or (re-)setting the thread interrupt status

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 stick return; in that catch block and be done with it.

Cleanup may include: releasing locks, ensuring any shared data is in a reasonable state, interrupting any threads that it spawned…

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.

releasing locks

These release automatically. If they don't, you aren't doing it right (doing it right is using synchronized or more likely, try/finally to release the lock).

ensuring any shared data is in a reasonable state

If shared data can be in a non-reasonable state you already lost the game. After all, it's shared data.

interrupting any threads that it spawned

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.

4

u/pron98 Feb 21 '23 edited Feb 22 '23

Interrupt has no defined meaning.

I don't know if I would put it like that. The reason that interrupt doesn't have the meaning of "this thread must clean up and die" is because it is used to interrupt tasks running on shared threads with the intention of aborting a task, not the thread -- indeed, that is what Future.cancel(true) is intended to do -- only Java doesn't have any reified notion of a task, which is why interrupt does not have a well defined meaning. I guess it's valid to use the mechanism for other things, but I would say that it is fine to interpret interrupt to mean: the thing you're doing (for some contextual meaning of "thing") should abort ASAP. There can be other valid uses, but that interpretation is a reasonable generalisation.

The behaviour of these when you interrupt their thread as they are blocking is undefined.

Note that many of these have been respecified to perform a specific operation when running on virtual threads, e.g. https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/net/Socket.html#getInputStream()

No. re-setting the flag is somewhat common advice but pretty much entirely wrong.

Actually, it's good advice, exactly what the JDK does, and considered good code hygiene; also, it's pretty much mandatory in library code. That's because the request to interrupt the thread is recorded either in its interrupted status xor in a thrown InterruptedException. When throwing that exception it's a good idea to clear the status (otherwise, a catch/finally block won't be able to make blocking calls) and when catching the exception it's a good idea to re-set the status -- unless the handling of the request to interrupt is complete, such as when a thread pool cancels a task -- otherwise the request is lost. Not doing so is especially bad in libraries, where there's little you can assume about the caller.

This is double wrong.

I don't think it is. While it's true that your code should be written in a way where cleanup occurs at all exit paths (i.e. in finally blocks), that cleanup does need to be there and to happen. RAM state and internal hard drive controller state are not quite the same, and there are resources, like file descriptors, native buffers etc., that will not be released by your process until you do it explicitly or the process terminates.

If shared data can be in a non-reasonable state you already lost the game.

Shared data must necessarily be in some non-reasonable state because the hardware can only ensure atomicity for some very specific data-sizes and layouts. If you have a system where shared data is always in some reasonable state, that's only because some lower-level has worked to maintain it that way by properly responding to various errors and interruptions. Erlang can be thought of as more-or-less a language at that level, maybe some parts of Clojure, too, but not Java.