Member-only story
AtomicInteger class in Java
2 min readSep 18, 2023
In Java, the AtomicInteger
class is part of the java.util.concurrent.atomic
package, which provides a set of atomic variables that support atomic operations. An atomic operation is an operation that is executed as a single, uninterruptible unit, ensuring thread safety in a multithreaded environment. The AtomicInteger
class specifically deals with atomic operations on integer values.
The AtomicInteger
class provides methods to perform operations like:
get()
: Gets the current value of theAtomicInteger
atomically.set(int newValue)
: Sets the value of theAtomicInteger
to a specified integer.getAndSet(int newValue)
: Atomically sets the value to a new integer and returns the old value.compareAndSet(int expect, int update)
: Atomically compares the current value to an expected value and updates it if the comparison succeeds.- Various atomic arithmetic operations like
incrementAndGet()
,decrementAndGet()
,addAndGet(int delta)
, and more.
Here’s an example of using AtomicInteger
to perform atomic increments:
package com.tipsontech.demo;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
public static void main(String[] args) {
// Create an AtomicInteger with an initial value of…