4

Does anyone know why the java.util.Spliterator implementation uses do-while rather than while loops, when the body of the loop is empty? For instance, the implementation of forEachRemaining is:

default void forEachRemaining(Consumer<? super T> action) {
    do { } while (tryAdvance(action));
}

Why would they use

do { } while (tryAdvance(action));

instead of

while(tryAdvance(action));

?

Are there any advantages I am not aware of?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
erdal.karaca
  • 693
  • 1
  • 4
  • 20
  • so both loops run, as long as the termination condition `tryAdvance(action)` returns true. – Mad Matts May 19 '16 at 12:49
  • 1
    While this is certainly a duplicate, I think that the accepted answer in the other question does not really answer the question (instead, it raises new ones...) – Marco13 May 19 '16 at 13:19
  • 3
    The choice was made purely on style. The other two ways of writing it (`while (c());` and `while (c()) {}`), when reading the code, both seemed to raise questions along the lines of "is this really what the author meant?", whereas the form we settled on seemed to express the intent most clearly. Your opinion may vary. – Brian Goetz May 19 '16 at 15:17
  • @BrianGoetz So, if it was a matter of style, then, it has nothing to do with the hidden synchronization which is implied in the answers of the other question? – erdal.karaca May 19 '16 at 15:33
  • 1
    Not in this case; the computation in this case is purely thread-local. – Brian Goetz May 19 '16 at 15:55

1 Answers1

-2

The logic check executes after the body of the do{}. This can be utilized many ways but does the same thing as a while loop with logic check at the end. Because the do{} is empty the thread will wait until notified and then execute the logic check rather than execute the logic check then if true wait.

Czarking
  • 143
  • 1
  • 10
  • What thread are you talking about? Is there any (hidden) synchronization invloved? – erdal.karaca May 19 '16 at 12:53
  • 3
    "[...] Because the do{} is empty the thread will wait until notified [...]" This does not make sense. If some synchronization takes place, it can only be within the condition. Why should it matter whether the condition is at the start or the end of the loop? – Turing85 May 19 '16 at 12:53