-2

I need to increment AtomicInteger twice, like: ++i; ++i; By the endless ciycle, i want to increment counter twice and check it on the parity. But i'm always getting the variable which was incremented once. How to fix it?

2 Answers2

13
    AtomicInteger counter = new AtomicInteger(100);
    counter.addAndGet(2);
    System.out.println(counter);

or

    AtomicInteger counter = new AtomicInteger(100);        
    counter.incrementAndGet();
    counter.incrementAndGet();
    System.out.println(counter);
Eritrean
  • 15,851
  • 3
  • 22
  • 28
3

Gives me an even number every time:

import java.util.concurrent.atomic.AtomicInteger;

public class HelloWorld {
  public static void main(String[] args) {
        AtomicInteger counter = new AtomicInteger(100);
        int limit = 100;
        while ( limit-- != 0 ){
            counter.incrementAndGet();
            counter.incrementAndGet();
            System.out.println(counter.get());
        }
  }
}
didiz
  • 1,069
  • 13
  • 26
  • I suppose there aren't, unless atomic guarantees that stuff won't be optimized away, or something esoteric like that. http://stackoverflow.com/questions/9749746/what-is-the-difference-between-atomic-volatile-synchronized – didiz May 10 '17 at 12:16
  • 2
    AFAIK the point of atomics is in case another thread changes a value. If you've only got one thread, there's no reason to use them. – Steve Smith May 10 '17 at 12:49