I am executing a java code where I have an AtomicInteger
on which 1000 threads are trying to perform an incrementAndGet()
. I was expecting the final value to be 1000. But each run is generating all sorts of different values. The code is as follows :
class task implements Runnable {
AtomicInteger i ;
task(AtomicInteger ai) {i =ai ;}
public void run() { i.incrementAndGet() ; }
}
class jlt {
public static void main(String[] args) throws Exception {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
for(int i=1; i<=1000; i++)
executor.submit(new task(atomicInt)) ;
executor.shutdown() ;
System.out.println(atomicInt.get()); // 1000 is expected
}
}
I am not able to figure out the mistake that I am making here or in my understanding
AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.
It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization.
incrementAndGet() – Atomically increments the current value by 1 and returns new value after the increment. It is equivalent to ++i operation. getAndIncrement() – Atomically increment the current value and returns old value. It is equivalent to i++ operation.
New! Save questions or answers and organize your favorite content. Learn more.
You're not waiting for the threads to finish before printing out the number.
Add a executor.awaitTermination(10, TimeUnit.SECONDS)
after shutdown()
and you might see something that you expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With