Thursday, January 29, 2026
HomeLanguagesJavaAtomicReference updateAndGet() method in Java with Examples

AtomicReference updateAndGet() method in Java with Examples

The updateAndGet() method of a AtomicReference class is used to atomically updates which updates the current value of the AtomicReference by applying the specified updateFunction operation on the current value. It takes an object of updateFunction interface as its parameter and applies the operation specified in the object to the current value. It returns the updated value.

Syntax:

public final V 
  updateAndGet(UnaryOperator<V> updateFunction)

Parameters: This method accepts updateFunction which is a side-effect-free function.

Return value: This method returns the updated value.

Below programs illustrate the updateAndGet() method:
Program 1:




// Java program to demonstrate
// AtomicReference.updateAndGet() method
  
import java.util.concurrent.atomic.*;
import java.util.function.UnaryOperator;
  
public class GFG {
    public static void main(String args[])
    {
  
        // AtomicReference with value
        AtomicReference<Integer> ref
            = new AtomicReference<>(987654);
  
        // Declaring the updateFunction
        // applying function
        UnaryOperator function
            = (v) -> Integer.parseInt(v.toString()) * 2;
  
        // apply updateAndGet()
        int value = ref.updateAndGet(function);
  
        // print AtomicReference
        System.out.println(
            "The AtomicReference updated value: "
            + value);
    }
}


Output:

Program 2:




// Java program to demonstrate
// AtomicReference.updateAndGet() method
  
import java.util.concurrent.atomic.*;
import java.util.function.UnaryOperator;
  
public class GFG {
    public static void main(String args[])
    {
  
        // AtomicReference with value
        AtomicReference<String> ref
            = new AtomicReference<>("welcome");
  
        // Declaring the updateFunction
        // applying function to add value as string
        UnaryOperator twoDigits
            = (v) -> v + " to gfg";
  
        // apply updateAndGet()
        String value
            = ref.updateAndGet(twoDigits);
  
        // print AtomicReference
        System.out.println(
            "The AtomicReference current value: "
            + value);
    }
}


Output:

References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#updateAndGet(java.util.function.UnaryOperator)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32476 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6848 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6916 POSTS0 COMMENTS