Report this

What is the reason for this report?

AtomicInteger in Java

Published on August 4, 2022
AtomicInteger in Java

Today we will look into AtomicInteger in Java. Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.

AtomicInteger

AtomicInteger, java atomicinteger, atomic integer Let’s create a simple multi-threaded program where every thread increments the shared count variable 4 times. So if there are two threads, after they finish count value should be 8. JavaAtomic.java

package com.journaldev.concurrency;

public class JavaAtomic {

    public static void main(String[] args) throws InterruptedException {

        ProcessingThread pt = new ProcessingThread();
        Thread t1 = new Thread(pt, "t1");
        t1.start();
        Thread t2 = new Thread(pt, "t2");
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Processing count=" + pt.getCount());
    }

}

class ProcessingThread implements Runnable {
    private int count;

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count++;
        }
    }

    public int getCount() {
        return this.count;
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

If you will run above program, you will notice that count value varies between 5,6,7,8. The reason is because count++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomic operation without usage of Synchronization.

Java AtomicInteger Example

Here is the updated program that will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one.

package com.journaldev.concurrency;

import java.util.concurrent.atomic.AtomicInteger;

public class JavaAtomic {

    public static void main(String[] args) throws InterruptedException {

        ProcessingThread pt = new ProcessingThread();
        Thread t1 = new Thread(pt, "t1");
        t1.start();
        Thread t2 = new Thread(pt, "t2");
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Processing count=" + pt.getCount());
    }
}

class ProcessingThread implements Runnable {
    private AtomicInteger count = new AtomicInteger();

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            processSomething(i);
            count.incrementAndGet();
        }
    }

    public int getCount() {
        return this.count.get();
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Benefits of using Concurrency classes for atomic operation is that we don’t need to worry about synchronization. This improves code readability and chance of errors are reduced. Also atomic operation concurrency classes are assumed to be more efficient that synchronization which involves locking resources.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
Tags:
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Was this helpful?

Thank you very much for your site and tutorials! You are doing very great job, even after almost 7 years in java development i can find something new in your blog posts! Thank you very much and good luck!

- Alex

nice blog sir…thanks a lot…

- suresh

Thanks a lot this tutorial.

- Dharmendra Sahu

How is atomicity incorporated into the Atomic Integer class? it has to be via locks right ?? Then how is this different from Synchronisation block?

- Sorrowfull Blinger

Hi, Simply i can modify the program you suggested above for atomic but i haven’t seen any benefit of this atomic variable because in both cases i am getting same result. So can you please provide another example for the same to see what exactly it is… package test; import java.util.concurrent.atomic.AtomicInteger; public class JavaAtomic { public static void main(String[] args) throws InterruptedException { ProcessingThread pt = new ProcessingThread(); Thread t1 = new Thread(pt, “t1”); Thread t2 = new Thread(pt, “t2”); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(“Processing count=” + pt.getCount()); } } class ProcessingThread implements Runnable { // private AtomicInteger count = new AtomicInteger(); int count = 0; @Override public void run() { // count.incrementAndGet(); for (int i = 0; i < 4; i++) { count++; } } public int getCount() { // return this.count.get(); return count; } }

- sachin

Good site for java interview preparation. But i didn’t understand why to use Atomic integer class. Can you please provide the scenario where we can use this

- Lalita

it’s very usefully for me ,this is my first time visited this site.The tutorials understandability,thanks a lot.But i didn’t understand how to use Atomic integer class?

- Wells Lee

I think the count value going “5,6,7,8” is perfectly acceptable in your first example isn’t it? But Yes. I got the concept.

- IM

This is a wrong explanation u r joining both threads . Did not expect this dumb kind of explanation from such a senior analyst. Clear ur concepts first.

- Nitin

I think we need better explanation, not just the syntax on how to use AtomicInteger, its available everywhere else on the internet.

- Prashant

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.