I came across the following example on winterbe.com which is demonstrating the use of Atomic variables.
// From http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/
public class Test_AtomicInteger {
public static void main(String[] args) {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 1000)
.forEach(i -> {
Runnable task = () ->
atomicInt.updateAndGet(n -> n + 2);
executor.submit(task);
});
executor.shutdownNow();
System.out.println(atomicInt.get()); // => 2000
}
}
Understand how the expected value 2000 is deduced from a Thread-Safe scenario. However, when I tried to execute it on eclipse IDE, it gives a different output value every time on each run. Would like see if anyone knows why it behaves like this. Thanks a lot.