Member-only story

AtomicInteger class in Java

Saurav Kumar
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:

  1. get(): Gets the current value of the AtomicInteger atomically.
  2. set(int newValue): Sets the value of the AtomicInteger to a specified integer.
  3. getAndSet(int newValue): Atomically sets the value to a new integer and returns the old value.
  4. compareAndSet(int expect, int update): Atomically compares the current value to an expected value and updates it if the comparison succeeds.
  5. 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…

--

--

Saurav Kumar
Saurav Kumar

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet