Object.wait returns normally if interrupted
David Holmes
david.holmes at oracle.com
Fri Jun 27 02:47:23 UTC 2025
Hi Pavel,
On 27/06/2025 8:23 am, Pavel Rappo wrote:
> Here's an interesting behaviour. A thread that has been blocked in
> Object.wait is interrupted. But instead of throwing an
> InterruptedException, Object.wait returns normally with the thread's
> interrupt status set.
Do you mean it returns normally without being notified? That's allowed
by spec as it is just a spurious wakeup.
That said, it shouldn't really happen in the current implementation
AFAIK, though with recent changes around virtual thread support it is
possible some new edge case has crept in. Or a bug.
If the interrupt is racing with a notification then what you see is also
allowed as you can't tell which occurred first:
"If the current thread is interrupted by any thread before or while it
is waiting, ...
once notified it is no longer waiting.
> This behaviour is not mentioned in javadoc, yet I witnessed it.
> Granted, I could only trigger it in an edge case described in JLS. I
What edge case is described in current JLS?
> wonder if the behaviour is reserved for that edge case, or it can be
> observed elsewhere and there is a genuine gap in javadoc. FWIW,
> javadoc for j.u.c.Condition documents this behaviour.
>
> Here's a practical implication of this. If some code that uses
> Object.wait wants to be interruptible, it must not rely on Object.wait
> to throw InterruptedException. It should check interrupt status or
> call other methods that are guaranteed to throw InterruptedException
> on thread interruption.
In typical usage though if you were notified as well then responding to
that is generally fine and is what would happen if the notification
definitely occurred before the interrupt. If it was a spurious wakeup
then you should be re-waiting in a loop and the next wait will throw the
IE. So I think no real code would be adversely impacted by these edge cases.
Cheers,
David
-----
> -Pavel
More information about the core-libs-dev
mailing list