What is the AtomicInteger.set() method in Java?
AtomicInteger represents an integer value the may be updated AtomicInteger is present in the java.util.concurrent.atomic package.
This
will give you a greater understanding of the atomic concept. article https://www.digitalocean.com/community/tutorials/atomicinteger-java
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
AtomicIntegerclass. -
In line number 4, we created a new object for the
AtomicIntegerclass with the nameatomicIntegerand with the value10. -
In line number 8, we used the
set()method of theatomicIntegerto set the value of theatomicIntegerto 100. We also used theget()method to get the value of theatomicIntegerobject and printed it.