DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building an AI-Powered Code Review Assistant in Java
  • Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't
  • From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade

Trending

  • The "Just Read the Code" Myth Is Killing Your AI Workflow
  • Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs
  • Tracing Dangerous Python Code Paths With rce-path
  • Every Acquisition Promises One Company. Most Deliver Two.

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java Concurrency: Atomic Variables

Java Concurrency: Atomic Variables

Expand your Java concurrency knowledge by taking a closer look at atomic variables and how to execute them in your code.

By 
Akshansh Jain
·
Jun. 27, 19 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
36.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In today’s blog, we will be discussing and understanding the use of atomic variables with regards to concurrency in Java. But before understanding atomic variables, let’s understand what do we mean by atomic or atomicity.

Atomicity

Atomic operations are those operations that ALWAYS execute together. Either all of them execute together, or none of them executes. If an operation is atomic, then it cannot be partially complete, either it will be complete, or not start at all, but will not be incomplete.

Consider the following example:

public class Atomicity {

    int i;

    public void incrementNumber() {
        i = 1;
    }
}


In the above example, we are writing value 1 to an int i. This is an atomic operation since this will either happen all together, assigning 1 to i, or it won’t happen at all. This property of an operation, or a set of operations, being atomic is known as atomicity.

Now, consider the following example:

public class Atomicity {

    int i;

    public void incrementNumber() {
        i = i + 1;
    }
}


At first glance, this might seem like an atomic operation, but it is actually not. This one-liner actually consists of three operations.

  • Read operation, where the value of i is read.
  • Modify operation, where a new value is being calculated (i + 1).
  • Write operation, where the new value is written to the variable i.

Now, since these operations are separate, these set of operations are currently not atomic, since it is possible for them to partially execute. This might be a little hard to understand in a single-threaded environment, but just imagine running this piece of code on multiple threads. If we call this method two times on a single thread, it will result in i being equal to 2. But imagine calling it on two threads. The result should ideally remain the same, but if we call this method on two threads at the same time, then thread A and B will both read the value at the same time and update the value at the same time as well, resulting i to be equal to 1. This is happening because the set of operations here are not atomic. Let’s see how we can make these set of operations atomic.

Atomic Variables

Atomic variables come to the rescue in these types of situations. Atomic variables allow us to perform atomic operations on the variables.

Consider the following example:

import java.util.concurrent.atomic.AtomicInteger;

public class Atomicity {

    AtomicInteger i;

    public void incrementNumber() {
        i.incrementAndGet();
    }
}


The above example shows how an AtomicInt can be used to update the value atomically. What incrementAndGet()  does is atomically increment the value by 1, and then returns the updated value. If the program is now run in a multi-threaded environment, supposing with 2 threads, then the end result will always be i being equal to 2. This is because no matter which thread gets to the incrementAndGet() method first, since it is an atomic operation, the thread will update the value of i to 1, and only then another thread will be able to access or update it, which will make the value of i to 2, thus giving us the correct result.

The most commonly used atomic classes are – AtomicInt, AtomicLong, AtomicBoolean, and AtomicReference. All of these provide atomic operations for the respective classes. AtomicReference can be used for just any type of object.

Conclusion

When programming in a multi-threaded environment, we need to avoid situations in which concurrent execution of a set of operations may lead to incorrect or unexpected behavior. So, we need to make these set of operations atomic. For operations on a single variable, we can achieve this by using the atomic variable classes, which offers us atomic operations on the variables, thus achieving correct behavior in a multi-threaded environment.

I hope this blog was helpful to you, and you learned something from it. I will be writing more blogs regarding Java concurrency as well. Until then, happy blogging!

Java (programming language)

Published at DZone with permission of Akshansh Jain. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building an AI-Powered Code Review Assistant in Java
  • Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't
  • From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook