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
}