Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do "nothing" while "condition"

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?

like image 296
Erik Vesteraas Avatar asked Jul 07 '14 11:07

Erik Vesteraas


People also ask

What is the do-while condition statement?

Syntax. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.

Can I have an empty while loop?

Empty while loopsAn empty while loop is a bad idea. This isn't the best approach but it is an acceptable one (in the right scenario). This ensures that you only perform the check at a reasonable interval. Note that the precise length of that interval is up to you to decide.

Do-while loops need a condition?

In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed.

Do-while condition is false?

The do while construct consists of a process symbol and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false.


1 Answers

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). 
like image 79
MicSim Avatar answered Oct 06 '22 00:10

MicSim