Sunday, January 18, 2026
HomeLanguagesJavaAtomicLong getAndUpdate() method in Java with Examples

AtomicLong getAndUpdate() method in Java with Examples

The Java.AtomicLong.getAndUpdate() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value. It takes an object of LongUnaryOperator interface as its parameter and applies the operation specified in the object to the current value. It returns the previous value.

Syntax:

public final long getAndUpdate(LongUnaryOperator function)

Parameters: This method accepts as parameter an LongUnaryOperator function.
It applies the given function to the current value of the object.

Return Value: The function returns the previous value of the object.

Example to demonstrate the function.




import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongUnaryOperator;
  
public class Demo {
    public static void main(String[] args)
    {
        // AtomicLong initialized with a value of -20000
        AtomicLong al = new AtomicLong(-20000);
  
        // Unary operator defined to negate the value
        LongUnaryOperator unaryOperator = (x) -> - x;
  
        // Function called and the unary operator
        // is passed as an argument
        long x = al.getAndUpdate(unaryOperator);
        System.out.println("Previous value is " + x);
        System.out.println("Updated Value is " + al);
    }
}


Output:

Previous Value is -20000
Updated value is 20000

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html

RELATED ARTICLES

Most Popular

Dominic
32474 POSTS0 COMMENTS
Milvus
118 POSTS0 COMMENTS
Nango Kala
6846 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12063 POSTS0 COMMENTS
Shaida Kate Naidoo
6985 POSTS0 COMMENTS
Ted Musemwa
7219 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6911 POSTS0 COMMENTS