34

I was looking inside the AtomicInteger Class and I came across the following method:

/**
 * Atomically increments by one the current value.
 *
 * @return the previous value
 */
public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}

Can someone explain what for(;;) means?

Shawn
  • 7,235
  • 6
  • 33
  • 45
  • 1
    I'll leave this here just in case you're a visual learner. :) http://i.stack.imgur.com/3Jlif.jpg – mre Apr 15 '11 at 13:19

5 Answers5

58

It is equivalent to while(true).

A for-loop has three elements:

  • initializer
  • condition (or termination expression)
  • increment expression

for(;;) is not setting any of them, making it an endless loop.

Reference: The for statement

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 4
    It should be noted that traditionally `for(;;)` is the canonical endless loop, particularly in C. – Joachim Sauer Apr 15 '11 at 13:05
  • 2
    What is the advantage to using `for(;;)` over `while(true)`? EDIT: I was able to answer my own question with a simple Google search: no difference and they compile to the same result. https://stackoverflow.com/questions/8880870/java-for-vs-whiletrue – robere2 Apr 08 '18 at 02:18
9

It's the same thing as

while(true) {
    //do something
}

...just a little bit less clear.
Notice that the loop will exit if compareAndSet(current, next) will evaluate as true.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
3

It's just another variation of an infinite loop, just as while(true){} is.

Esko
  • 29,022
  • 11
  • 55
  • 82
2

That is a for ever loop. it is just a loop with no defined conditions to break out.

John Kane
  • 4,383
  • 1
  • 24
  • 42
2

It's an infinite loop, like while(true).

Isaac Truett
  • 8,734
  • 1
  • 29
  • 48