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?
Solution 1:
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).
Solution 2:
ForkJoinPool
makes extensive use of compareAndSwap...
from sun.misc.Unsafe
and most of the occurrences of do {} while (...)
in ForkJoinPool
can — as mentioned by other answers — be explained by this comment under the heading 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.
The choice to use write a while
-loop with an empty body as do {} while (condition)
seems however to be a mostly stylistic choice. This is perhaps clearer in HashMap
, which happened to be updated in Java 8.
In the Java 7 HashMap
you can find this:
while (index < t.length && (next = t[index++]) == null)
;
While much of the code around it has also changed, it is clear that the replacement in Java 8 is this:
do {} while (index < t.length && (next = t[index++]) == null);
The first version has the weakness that if the lone semicolon happened to be deleted it would change the meaning of the program depending on the following line.
As seen below, bytecode generated by while (...) {}
and do {} while (...);
is slightly different, but not in any way that should affect anything when run.
Java code:
class WhileTest {
boolean condition;
void waitWhile() {
while(!condition);
}
void waitDoWhile() {
do {} while(!condition);
}
}
Generated code:
class WhileTest {
boolean condition;
WhileTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
void waitWhile();
Code:
0: aload_0
1: getfield #2 // Field condition:Z
4: ifne 10
7: goto 0
10: return
void waitDoWhile();
Code:
0: aload_0
1: getfield #2 // Field condition:Z
4: ifeq 0
7: return
}