I took this code from a tutorial on atomics, it stated :-
"By using AtomicInteger as a replacement for Integer we're able to increment the number concurrently in a thread-safe manor without synchronizing the access to the variable. The method incrementAndGet() is an atomic operation so we can safely call this method from multiple threads."
It said this would return the correct result, 1000 however neither instance reaches 1000, they are usually considerably less, e.g.
test1 result = 532
test2 result = 128
Whats wrong ?
public class AtomicsTest {
public static void main(String... args){
AtomicsTest test = new AtomicsTest();
test.test1();
test.test2();
}
public void test1() {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newSingleThreadExecutor();
IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
System.out.println("test1 result = "+ atomicInt.get());
executor.shutdown();
}
public void test2() {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
System.out.println("test2 result = " + atomicInt.get());
executor.shutdown();
}
}