What is the AtomicInteger.getAndSet method in Java?

What is the AtomicInteger.getAndSet method in Java? Answer

An AtomicInteger represents an integer value that may be updated atomically.

Atomic operations perform a single unit of work on a resource. During that operation, no other operations are allowed on the same resource until the performing operation is finished.

The AtomicInteger class is present in the java.util.concurrent.atomic package.

This article may help you get a greater understanding of the atomic concept.

The getAndSet method of the AtomicInteger class atomically updates the given value as the current value of the AtomicInteger and returns the previous value.


public final int getAndSet(int newValue)


This method takes the new value of the AtomicInteger object as an argument.

Return value

This method returns the previous value of the AtomicInteger.


The code below demonstrates how to use the getAndSet method.

import java.util.concurrent.atomic.AtomicInteger;
class GetAndSet{
  public static void main(String[] args) {
    AtomicInteger atomicInteger = new AtomicInteger(10);
    int val = atomicInteger.get();
    System.out.println("The value in the atomicInteger object is " + val);

    System.out.println("\nCalling atomicInteger.getAndSet(5)");
    val = atomicInteger.getAndSet(5);
    System.out.println("\nThe old Value is : " + val);
    System.out.println("The new Value is : " + atomicInteger.get());


  • Line 1: We import the AtomicInteger class.
  • Line 4: We create a new object for the AtomicInteger class with the name atomicInteger and with the value 10.
  • Line 9: We use the getAndSet method with 5 as an argument. This method will update the passed value (5) as the current value and return the old value (10).
What is the AtomicInteger.getAndSet method in Java? Review:

In our experience, we suggest you solve this What is the AtomicInteger.getAndSet method in Java? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the What is the AtomicInteger.getAndSet method in Java?

Find on Educative


I hope this What is the AtomicInteger.getAndSet method in Java? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *