Sameera De Silva
4 min readApr 20, 2023

AtomicInteger in Java

what is it ?

AtomicInteger is a Java class that enables storing and manipulating integer values in a thread-safe manner. It acts as a wrapper around an integer value and can be accessed and modified atomically by multiple threads, ensuring synchronization and preventing data races and other synchronization issues.

The class doesn’t require explicit locking or unlocking, which makes it easier to use in multi-threaded environments, unlike traditional locks. Additionally, AtomicInteger can offer better performance in specific scenarios due to its lock-free implementation.

Finally, AtomicInteger provides a straightforward and intuitive API, making it easy to use and understand..

Used for countersAtomicInteger is often used to implement counters in multi-threaded application.

When not to use it ?

  • If only a single thread will be accessing and modifying the integer variable, then regular integer operations may be sufficient
  • If you require more complex synchronization or locking mechanisms, such as using condition variables or wait/notify constructs, then AtomicInteger may not be appropriate
  • If the cost of using AtomicInteger is greater than the benefit, such as when the variable is only modified infrequently or the performance gain is minimal, then regular integer operations may be a better choice.

How AtomicInteger is differnet from Integer, and int

How to declare

If you don’t provide an initial value, the default value of an AtomicInteger0.

Or else we can give with initial value as well.

AtomicInteger num = new AtomicInteger(0);
AtomicInteger num = new AtomicInteger();
private AtomicInteger numPeople = new AtomicInteger(0);

Methods in AtomicInteger are summarized in below table.

First , lets look at the get()

Return Type=int
Gets the current value of the AtomicInteger.

    public static void main(String[] args) {
AtomicInteger minute = new AtomicInteger(10);
int currentValue = minute.get();
minute.getAndSet(minute.get()+1);
// also, we can get current value and increment by 1.
System.out.println("Current value-"+minute);
// 11 should be printed.
}

Then lets look at set()

Return Type=void
Sets the value of the AtomicInteger to newValue.

    public static void main(String[] args) {
AtomicInteger minute = new AtomicInteger(10);
int oldValue = minute.get();
System.out.println("Old value-"+oldValue);
// 10 should be printed.
minute.set(25);
System.out.println("Current value-"+minute);
// 25 should be printed.
}

Secondly, let’s look at the getAndIncrement()

Return Type=int
Atomically increments the value of the AtomicInteger by 1 and returns the old value.

Code example

    public static void main(String[] args) {
AtomicInteger minute = new AtomicInteger(0);
int oldValue = minute.getAndIncrement();
// Value of minute, will be increased by 1.
System.out.println("Current value-"+minute);
//1 should be printed
System.out.println("old Value value-"+oldValue);
// 0 should be printed
}

Now let’s look at the getAndSet(int newValue)

Return Type=int

Atomically sets the value of the AtomicInteger to the given newValue and returns the old value.

    public static void main(String[] args) {
AtomicInteger minute = new AtomicInteger(10);
int oldValue = minute.getAndSet(20);
System.out.println("Current value-"+minute); //1 should be printed
System.out.println("old Value value-"+oldValue); // 0 should be printed
minute.getAndSet(minute.get()+1); // also, we can get current value and increment by 1.
// Storing returned old value is optional.
System.out.println("Current value-"+minute); // 21 should be printed.
}

compareAndSet(int expectedValue, int newValue) method

is used to atomically compare the current value of an AtomicInteger with an expected value,
and if they are equal, update the value to a new value.
It returns a boolean value indicating whether the update was successful or not.

Return Type=boolean

  public static void main(String[] args) {
AtomicInteger num = new AtomicInteger(10);
System.out.println("Current value: " + num.get());
// Output: Current value: 10

boolean success = num.compareAndSet(10, 20);
if (success) { //Similar as (success==true)
System.out.println("New value: " + num.get());
// Output: New value: 20
} else {
System.out.println("Update failed.");
}
}

Now lets look at addAndGet() and getAndAdd()

The addAndGet(int delta) method adds the specified value (delta) to the current value of the AtomicInteger and returns the updated value.
current value=5 specified value=3 so returned value is 8.

        AtomicInteger atomicInt = new AtomicInteger(5);
// adds 3 to 5 and returns 8
int newAddAndGetValue = atomicInt.addAndGet(3);
// prints "New value: 8"
System.out.println("New value: " + newAddAndGetValue);
// prints "Updated atomicInt value: 8"
System.out.println("Updated atomicInt value: " + atomicInt.get());

The getAndAdd(int delta) method, on the other hand, returns the current value(Original) of the AtomicInteger and then adds the specified value (delta) to the current value

current value=5 specified value=3 so returned value is 5

        AtomicInteger atomicInt = new AtomicInteger(5);
// returns 5 (previous value) and then adds 3, so the new value is 8
int originalValue = atomicInt.getAndAdd(3);
// prints "Original value: 5"
System.out.println("Original value: " + originalValue);
// prints "Updated atomicInt value: 8"
System.out.println("Updated atomicInt value: " + atomicInt.get());
}

No responses yet