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?
Asked
Active
Viewed 1.5k times
-2
-
2the question is not complete, add some code here to explain your question. – S Jayesh May 10 '17 at 11:46
-
1just call `AtomicInteger.incrementAndGet()`twice – Faheem May 10 '17 at 11:48
-
Achilles didn`t work correctly – Илья Александрович May 10 '17 at 11:49
-
Achilles ,near 10k iteration variable was incremented once – Илья Александрович May 10 '17 at 11:51
-
Achilles, i am sure – Илья Александрович May 10 '17 at 11:51
-
1share your code – Faheem May 10 '17 at 11:51
-
public int increment() { atomic.incrementAndGet(); atomic.incrementAndGet(); System.out.println(atomic.get()); return atomic.get(); } – Илья Александрович May 10 '17 at 11:54
-
1Your code works for me. How about we see all your code? And add it to the question, not as a comment. – Steve Smith May 10 '17 at 11:59
2 Answers
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
-
-
@ИльяАлександрович It works. Even if you put the incrementAndGet part into an infinite loop it still works. Did you put the initialization of the AtomicInteger (`final AtomicInteger counter = new AtomicInteger(100);`) into a loop as well by any chance? – OH GOD SPIDERS May 10 '17 at 12:10
-
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
-
2AFAIK 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