AtomicLong
represents a long value that may be updated AtomicLong
class is present in the java.util.concurrent.atomic
package.
public final long addAndGet(long valueToAdd)
The addAndGet()
method of the AtomicLong
class takes the value to be added and will atomically add this value to the current value of the AtomicLong
object and return the updated value.
The below code demonstrates how to use the addAndGet()
method:
import java.util.concurrent.atomic.AtomicLong;class AddAndGet{public static void main(String[] args) {AtomicLong atomicLong = new AtomicLong(10);long val = atomicLong.get();System.out.println("The value in the atomicLong object is " + val);System.out.println("\nCalling atomicLong.addAndGet(5)");val = atomicLong.addAndGet(5);System.out.println("\nThe value in the atomicLong object is " + atomicLong.get());}}
In line 1: We imported the AtomicLong
class.
In line 4: We created a new object for the AtomicLong
class with the name atomicLong
and with the value 10
.
In line 9: We used the getAndAdd()
method with 5 as an argument. This method will add the passed value (5
) to the already present value (10
) and return the new value (15
).