Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situations can do-while be more efficient than while?

While vs. do-while

While and do-while are functionally equivalent when the blocks are empty, although while seems more natural:

do {} while (keepLooping());
while (keepLooping()) {}

One typical use case of a while/do-while with an empty block is to force an update of atomic objects with a compareAndSet (CAS). For example the code below will increment a in a thread-safe way:

int i;
AtomicInteger a = new AtomicInteger();
while (!a.compareAndSet(i = a.get(), i + 1)) {}

Context

Several parts of java.util.concurrent use the do {} while (...) idiom for CAS operations and the javadoc of ForkJoinPool explains:

There are several occurrences of the unusual do {} while (!cas...) which is the simplest way to force an update of a CAS'ed variable.

Since they admit it is unusual, I suppose they meant best rather than simplest.

Question

Are there situations where do {} while (!cas) can be more efficient than while (!cas) {} and for what reasons?

like image 836
assylias Avatar asked May 08 '13 10:05

assylias


1 Answers

So a 'do while' means it will run the code in the while loop once. Then, it only runs the code inside the while loop if the condition is true.

Simple demonstration

boolean condition = false;

do{
  System.out.Println("this text displayed");
}while(condition == true);

Output "this text displayed"

Normal

while(condition == true){
 System.out.Println("this text displayed");
}

output ""

  • *no output displayed due to condition being false.

Why or where you would use do while, I havn't come accross the need to so I can't help you there. It's just a matter of identifying a problem/need, and using what you know to solve it.similar to lego-the mechanical kind not 'blocks'.

like image 145
kyle england Avatar answered Oct 11 '22 07:10

kyle england