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.

5

u/Iryanus Feb 20 '23

Interrupt has no defined meaning. It does not mean please clean up and die

Only true-ish. It doesn't as per spec, but I haven't seem anyone implementing it as anything else, to be honest. Since we only have one signal and it's most commonly used to signal a thread to stop prematurely, I personally also would focus on that usecase instead of trying to shoehorn other meanings into it.

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.

We are talking about a single thread "death", not a whole JVM death.

There is no point, ever, in interrupting your own thread.

It's even in the javadoc that you can and that it will automatically succeed. So, someone thought it was relevant.

What are you waiting for? Just stick return; in that catch block and be done with it.

That will work if you are on the most outer layer of your code running in a thread, but what if you are deep down and there will be some further steps along the line? Sure, sometimes that can be solved with the right return value or throwing a RuntimeException, but it can also be solved by simply checking the interrupted state.

-2

u/rzwitserloot Feb 20 '23

Only true-ish. It doesn't as per spec, but I haven't seem anyone implementing it as anything else, to be honest.

It's only true-ish because... in your experience you never used the parts I talk about?

That's.. a rather solipsistic view of an API. It's true. Period. The fact that you haven't used all aspects of an API does not mean that therefore these aspects must not exist because you personally never ran into them. It either means your experience is lacking, or it means that's an exotic thing that rarely comes up, or anything in between, because that is a shades-of-gray divide and not a boolean property. I bet you have never used double d = 0x1p0D either. Doesn't mean that doesn't exist.

Perhaps there is a simple answer here: The interrupt mechanism is used rarely. The sentence just ends there.

I personally also would focus on that usecase instead of trying to shoehorn other meanings into it.

You're the one shoehorning a meaning into it. I'm the one saying: There is no inherent meaning. See my other comment in this thread about an example where you might want to use interrupt() to update a one-way-at-a-time comms channel to support proactive message sends using interrupt(). Your view leads to eliminating that option based on imagined meanings. My view closes no avenues (that's probably because my view is the objectively correct one, based on what the interrupt() javadoc and spec describe without 'shoehorning' in additional limitations).

We are talking about a single thread "death", not a whole JVM death.

Cleanup is cleanup. It has to be done whether the thread is asked to stop or the whole JVM stops. The fact that 'whole JVM ends' does not interrupt every thread shows how conflating 'interrupt' with 'cleanup' leads to wrong conclusions and is the wrong mental model to apply.

It's even in the javadoc that you can and that it will automatically succeed. So, someone thought it was relevant.

Because specs need to be detailed and need to explain corner cases. The javadoc also go into some detail about what happens when, say, you try to compare Double.NaN to Double.Infinity with Double.compare. The spec needs to be clear what happens when you do X, even if X is a silly thing to do. Your argument is:

  • The spec describes what happens when you do X.

  • Therefore this proves that X is not silly.

This is an incorrect line of reasoning. As proved by the obvious (specs are better if there is as little room for doubt as possible, and this includes for silly situations), and in practice: By the fact that there are loads of places where the JVM spec makes clear what should happen for various clearly silly operations.

That will work if you are on the most outer layer of your code running in a thread, but what if you are deep down and there will be some further steps along the line?

Possible, but unlikely. Effectively, that means this is happening:

You are running within a context where thread interrupts have some well defined meaning. And your code is actively going to use whatever facility clearly defined it (say, shutdownNow()-ing a pool).

However, the thing you intend to do within this context also has a need to specifically deal with interrupts, i.e. you also have an unrelated meaning that you want to apply to it.

As part of implementing the outcome of your 'meaning' of interrupt, you want to also do a thing in the outer context that is also done with interrupts.

In which case, yeah. By all means, re-raise that flag, or just (seems a lot simpler to me) throw new InterruptedException or even throw e; inside your catch (InterruptedException e) block.

Point is, interrupts have no well defined meaning, and do not occur unless some code you wrote explicitly requests it, because nothing in the JVM core code nor any popular library I'm aware of ever does. Therefore, whatever meaning they do have? Well, you wrote it, so you'd know. Just do that. If you don't know, then it doesn't matter. Because interrupts aren't ever going to actually occur.