Do "nothing" while "condition"

Erik Vesteraas picture Erik Vesteraas · Jul 7, 2014 · Viewed 12.3k times · Source

While browsing the code for the Java 8 version of ForkJoinPool(which has a few interesting changes from Java 7) I ran across this construct (here):

do {} while (!blocker.isReleasable() &&
             !blocker.block());

I'm struggling with why you would write it like this instead of just

while (!blocker.isReleasable() &&
       !blocker.block());

Is it just a semantics/readability choice, since you could read the first construct as do "nothing" while "conditions"? Or is there some additional benefit I'm missing?

Answer

MicSim picture MicSim · Jul 7, 2014

If you read the comments at top of the file, just below the class declaration, there is a section which explains the use of this construct:

Style notes

===========

[...]

There are several occurrences of the unusual "do {} while
(!cas...)"  which is the simplest way to force an update of a
CAS'ed variable. There are also other coding oddities (including
several unnecessary-looking hoisted null checks) that help
some methods perform reasonably even when interpreted (not
compiled).