Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing AtomicInteger in Java in 1000 threads does not generate value 1000 [duplicate]

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

like image 577
user3282758 Avatar asked Oct 23 '17 12:10

user3282758


People also ask

How does AtomicInteger work in Java?

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.

Is AtomicInteger thread safe?

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.

How do you increment an atomic Integer?

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.

Is AtomicInteger slow?

New! Save questions or answers and organize your favorite content. Learn more.


1 Answers

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.

like image 101
Kayaman Avatar answered Sep 28 '22 08:09

Kayaman