What is the AtomicLong.get() method in Java?

AtomicLong represents a long value that may be updated atomically.

An atomic operation performs a single unit of work on a resource. During that operation, no other operations are allowed on the same resource until the operation is complete.

The AtomicLong is present in the java.util.concurrent.atomic package.

The get() method of the AtomicLong is used to get the value present in the AtomicLong object.

Syntax

public final long get()

Parameter

This method does not take any argument.

Return value

This method returns the value present in the AtomicLong object.

Code

The code below demonstrates the use of the get() method.

import java.util.concurrent.atomic.AtomicLong;
class Get{
public static void main(String[] args) {
// the value is 10
AtomicLong atomicLong = new AtomicLong(10);
// calling the get() method
long val = atomicLong.get();
// displaying the value
System.out.println("The value in the atomicLong object is " + val);
}
}

Explanation

Line 1: We import the AtomicLong class.

Line 5: We create a new object for the AtomicLong class with the name atomicLong and with the value 10.

Line 8: We use the get() method of the atomicLong and store it to the long variable val.

Line 11: We print the value.

Click here to learn about the getAndAdd() method of AtomicLong in Java.

Free Resources