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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Trending

  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  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 user avatar
Akshansh Jain
·
Jun. 27, 19 · Presentation
Likes (5)
Comment
Save
Tweet
Share
35.8K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!