Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the AtomicLong.incrementAndGet 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 that may be updated atomically. An atomic operation performs 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. AtomicLong is present in the java.util.concurrent.atomic package.

The incrementAndGet method of AtomicLong automatically increments the current value by 1 and returns the updated value of the AtomicLong object.

Syntax

public final long incrementAndGet()

Parameters

This method doesn’t take an argument.

Return value

This method returns the incremented value as a long.

Code

The code below demonstrates how to use the incrementAndGet method.

import java.util.concurrent.atomic.AtomicLong;
class IncrementAndGet{
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(10);
System.out.println("The value in the atomicLong object is " + atomicLong.get());
System.out.println("\nCalling atomicLong.incrementAndGet()");
long val = atomicLong.incrementAndGet();
System.out.println("The new Value is : " + val);
}
}
An example of the AtomicIncrement.incrementAndGet() menthod

Explanation

  • Line 1: We import the AtomicLong class.

  • Line 4: We create a new object for the AtomicLong class with the name atomicLong and value 10.

  • Line 9: We call the incrementAndGet method. This method increments the current value (10) by 1 and returns the new value (11).

RELATED TAGS

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