Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

getandset
atomicinteger
java
communitycreator

What is the AtomicInteger.getAndSet method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

Syntax

public final int getAndSet(int newValue)

Parameters

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

Return value

This method returns the previous value of the AtomicInteger.

Code

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());
}
}
Using the "getAndSet" method

Explanation

  • 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).

RELATED TAGS

getandset
atomicinteger
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring