Java atomicinteger
AtomicInteger
is a class in Java that provides atomic operations on an int
value. It is part of the java.util.concurrent.atomic
package and can be used to perform thread-safe operations on a shared integer variable.
An AtomicInteger
can be used in a multithreaded environment where multiple threads need to access and modify the same integer value. Some of the key methods available in the AtomicInteger
class are:
get()
: returns the current value of the integerset(int newValue)
: sets the value of the integer to the specified valuecompareAndSet(int expect, int update)
: atomically sets the value of the integer to the specified update value if the current value is equal to the specified expect valueincrementAndGet()
: atomically increments the value of the integer and returns the new valuedecrementAndGet()
: atomically decrements the value of the integer and returns the new valuegetAndAdd(int delta)
: atomically adds the specified delta value to the integer and returns the previous value
Here's an example of using AtomicInteger
in Java:
import java.util.concurrent.atomic.AtomicInteger; public class Example { public static void main(String[] args) { // create a new atomic integer with an initial value of 0 AtomicInteger counter = new AtomicInteger(0); // increment the counter int value1 = counter.incrementAndGet(); System.out.println("Value1: " + value1); // add 5 to the counter int value2 = counter.getAndAdd(5); System.out.println("Value2: " + value2); // check the value of the counter int value3 = counter.get(); System.out.println("Value3: " + value3); } }
In this example, we create a new AtomicInteger
with an initial value of 0. We then use the incrementAndGet()
method to atomically increment the value of the integer, and the getAndAdd()
method to atomically add 5 to the integer and return the previous value.
Finally, we use the get()
method to check the current value of the integer.
AtomicInteger
is a useful class for situations where multiple threads need to access and modify the same integer value in a thread-safe manner. It can be used in a variety of applications, such as counting, synchronization, and more.