What is the AtomicInteger.set() method in Java?

AtomicInteger represents an integer value the may be updated atomicallyAtomic operation is performing a single unit of work on a resource. During that operation, no other operations are allowed on the same resource until the performing operation is finished.. The AtomicInteger is present in the java.util.concurrent.atomic package.

This articlehttps://www.digitalocean.com/community/tutorials/atomicinteger-java will give you a greater understanding of the atomic concept.

The set() method of AtomicInteger can be used to set the value of the AtomicInteger object.

Syntax

public final void set(int newValue)

This method takes the value to be set in the AtomicInteger object as an argument.

This method doesn’t return any value.

Code

The below code demonstrates how to use the set() method:

import java.util.concurrent.atomic.AtomicInteger;
class Set{
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(10);
int val = atomicInteger.get();
System.out.println("The value in the atomicInteger object is " + val);
System.out.println("\nCalling atomicInteger.set(100)");
atomicInteger.set(100);
System.out.println("\nThe value in the atomicInteger object is " + atomicInteger.get());
}
}

Explanation

  • In line number 1, we imported the AtomicInteger class.

  • In line number 4, we created a new object for the AtomicInteger class with the name atomicInteger and with the value 10.

  • In line number 8, we used the set() method of the atomicInteger to set the value of the atomicInteger to 100. We also used the get() method to get the value of the atomicInteger object and printed it.

Free Resources