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

        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());



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

>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.

Leave a Reply