Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

atomiclong
getandset
java
communitycreator

What is the AtomicLong.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.

AtomicLong represents a long value the may be updated atomicallyAtomic operation is performing 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 AtomicLong is present in the java.util.concurrent.atomic package.

This article helps you for a greater understanding of the Atomic concept.

The getAndSet method of the AtomicLong will atomically update the given value as the current value of the AtomicLong and returns the value before updating(previous value).

Syntax

public final long getAndSet(long newValue)

This method takes the new value to be updated as the current value of the AtomicLong object as an argument.

This method returns the value before updating the passed value.

Code

The code below demonstrates how to use the getAndSet method:

import java.util.concurrent.atomic.AtomicLong;
class GetAndSet{
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(10);
long val = atomicLong.get();
System.out.println("The value in the atomicLong object is " + val);
System.out.println("\nCalling atomicLong.getAndSet(5)");
val = atomicLong.getAndSet(5);
System.out.println("\nThe old Value is : " + val);
System.out.println("The new Value is : " + atomicLong.get());
}
}

Explanation

In line number 1: We have imported the AtomicLong class.

In line number 4: Created a new object for the AtomicLong class with the name atomicLong and with the value 10.

In line number 9: Used the getAndSet method with 5 as an argument. This method will update the passed value(5) as the current value and returns the old value(10).

RELATED TAGS

atomiclong
getandset
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