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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With