RFR(s) #2: 6344935: (spec) clarify specifications for Object.wait overloads
Martin Buchholz
martinrb at google.com
Fri Aug 25 05:26:45 UTC 2017
On Thu, Aug 24, 2017 at 7:49 PM, David Holmes <david.holmes at oracle.com>
wrote:
> I have no further comments on the actual spec.
>
> Here's my suggestion for the timed-wait example :)
>
> while (true) {
> if (!condition)
> wait(timeout, nanos);
> else
> break; // condition holds
> <recompute timeout>
> if (timeout <= 0 && !condition)
> throw new TimedOutException();
> }
> // Perform action appropriate to condition
>
It's really hard to write a good wait loop.
Evaluating the condition in two places is a burden on the programmer.
(re)computing the timeout should happen just before calling wait to avoid
expense of e.g. calling nanoTime unnecessarily.
After returning from wait, it is very likely that the condition is now
satisfied, suggesting that the call to wait should be the last thing in the
loop body, and testing the condition should be the first thing.
Throwing TimeoutException is a last resort in j.u.c. We prefer to return a
*special value* (false or null).
More information about the core-libs-dev
mailing list