Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shared counter concurrent incrementation using atomic integer

Hi I am new to multithreading. Was trying to understand the concept of Atomic integer. I have a shared counter variable which is incremented by two threads

class MyCounterClass{
    volatile AtomicInteger sharedCounter = new AtomicInteger(0);

    public int incrementCounter() {
        for(int i = 0; i <10000; i++){
            // add 1
            sharedCounter.incrementAndGet();
        }

        return this.sharedCounter.get();
    }
}

public static void main(String[] args) throws InterruptedException {
        MyCounterClass myCounterClassObj = new MyCounterClass();
        Thread t1 = new Thread(() -> {
            System.out.println("Thread " + Thread.currentThread().getName() + " " +myCounterClassObj.incrementCounter());
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread " + Thread.currentThread().getName()+ " " + myCounterClassObj.incrementCounter());
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}

I thought my output from 2 threads will be 20000. But I am getting 20000 as output of one thread and other one shows some random value between 10000 and 20000.
Could anyone help me understand what is happening here

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s not showing "a random value" – it’s showing "a value between 10,000 and 20,000 inclusive". It has to be at least 10,000 because the thread that’s printing has incremented the counter 10,000 times, and it has to be at most 10,000 because the other thread will have incremented the counter at most 10,000 times.

It would only show 20,000 twice if both threads reached return this.sharedCounter.get() after both threads have completed all 10,000 increments. One thread is very likely to finish a bit before the other one – at which point the counter won’t be 20,000.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading