Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction💁
2.
What are atomic variables Java?
3.
Java Atomic Classes
4.
Why use Atomic Variables in Java❓
4.1.
Java
5.
Using Synchronisation
5.1.
Java
6.
Using Atomic Variables in Java
6.1.
Java
7.
Frequently Asked Questions
7.1.
What is the atomic concept of Java?
7.2.
What is atomic in multithreading?
7.3.
Are the Atomic Variables in Java thread-safe?
7.4.
What are the most commonly used types of Atomic Variables in Java?
7.5.
What package is associated with Atomic Variables in Java?
8.
Conclusion
Last Updated: Apr 20, 2024
Easy

Atomic Variables in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction💁

Java is an object-oriented, class-based, high-level programming language. It is based on the concept of WORA (write once use anywhere) for developer ease. Java classes are compiled into byte code. The compiled byte codes can be used on any platform supporting Java without recompiling the class.

We have eight primitive or native data types in Java, namely,

  • int
  • short
  • long
  • byte
  • float
  • double
  • boolean
  • char
Data Types

Also Read About, Multithreading in java

What are atomic variables Java?

Atomic variables in Java are variables that provide atomicity guarantees for certain operations performed on them. Atomicity means that these operations are indivisible and appear as if they occur instantaneously, without interference from other threads. In Java, atomic variables are part of the java.util.concurrent package and are used for concurrent programming to ensure thread safety without explicit synchronization.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Java Atomic Classes

Java Atomic Classes are a set of classes provided by the java.util.concurrent.atomic package that encapsulate primitive data types and provide atomic operations for concurrent programming. These classes ensure thread safety without the need for explicit synchronization mechanisms such as locks or synchronized blocks.

  • AtomicInteger, AtomicLong, AtomicBoolean, etc.: Java provides atomic classes for various primitive data types, including integers, longs, booleans, and references. These classes encapsulate their respective data types and provide atomic operations for reading, writing, and updating their values.
  • Atomic Operations: Atomic classes support atomic operations such as get(), set(), getAndSet(), compareAndSet(), incrementAndGet(), decrementAndGet(), and more. These operations are guaranteed to be performed atomically, without interference from other threads.
  • Compare-and-Set (CAS) Operation: Atomic classes typically use a technique called Compare-and-Set (CAS) to ensure atomicity. CAS is a non-blocking synchronization mechanism that allows a thread to update a variable's value only if its current value matches the expected value.
  • Thread Safety: Atomic classes ensure thread safety without the need for explicit synchronization. They provide a simpler and more efficient way to handle concurrent access to shared variables in multithreaded environments.
  • Performance Considerations: While atomic classes provide thread safety and simplicity, they may incur a slight performance overhead compared to non-atomic operations. However, in many cases, the benefits of thread safety outweigh the performance cost.

Why use Atomic Variables in Java

The Atomic Variables in Java come in handy in the case of concurrency. For instance, let us consider an example where we have to count the number of times a loop is running for multiple threads.

  • Java

Java

class threadCount extends Thread{
int total = 0;
public void run(){
int max = 100000;
for (int i = 0; i < max; i++){
sum++;
}
}
}

public class Main{
public static void main(String args[]) throws InterruptedException{
threadCount count = new threadCount();
Thread first = new Thread(count, "First");
Thread second = new Thread(count, "Second");
first.start();
second.start();
first.join();
second.join();
System.out. println("Loop count without using Atomic Variables in Java: "+count.total);
}
}
Thread Output

As is clearly visible from the above output, the program gives a different outcome for each execution. But is it supposed to happen? No, the program should return 200000 as the output for each execution. So why does it happen? The fault occurs because of concurrency. At times the threads may execute simultaneously, causing a write problem. We can overcome this using two methods,

  • Using Synchronization
  • Using Atomic Variables in Java

Read More About, Basics of Java, Why is Java Platform Independent

Using Synchronisation

We can solve the issue of concurrency using the synchronization function in Java.

  • Java

Java

import java.io.*;
import java.util.*;
class threadCount extends Thread {
int total = 0;
public synchronized void run(){
int max = 100000;
for (int i = 0; i < max; i++) {
total++;
}
}
}

public class usingSync {
public static void main(String args[])throws InterruptedException{
threadCount count = new threadCount();
Thread first = new Thread(count, "First");
Thread second = new Thread(count, "Second");
first.start();
second.start();
first.join();
second.join();
System.out. println("Loop count using Synchronisation: "+count.total);
}
}
Sync Output

As you can see, no matter how many times the program is executed, it returns the same and correct output. We can also achieve this using the Atomic Variables in Java.

Synchronization Image

Try it on java online compiler.

Using Atomic Variables in Java

Types of Atomic Variables

There are various methods present in Atomic Variables in Java, for example.

  • get(): This method is used to fetch the current value of the Atomic Variable in Java.
  • addAndGet(int val): This method is used to atomically add the given value to the current value of the Atomic Variable in Java.
  • decrementAndGet(): This method is used to decrease the value of the variable.

Users can create an instance of the Atomic Variable class and call these functions directly.

Let us look at how to implement the above problem using Atomic Variables in Java,

  • Java

Java

import java.util.concurrent.atomic.AtomicInteger;
class threadCount extends Thread {
//creating an instance of Atomic Variable Class
AtomicInteger total;
threadCount(){
total = new AtomicInteger();
}
public void run(){
int max = 100000;
for (int i = 0; i < max; i++) {
//Calling the addAndGet function
total.addAndGet(1);
}
}
}

public class usingAtomic {
public static void main(String args[])throws InterruptedException{
threadCount count = new threadCount();
Thread first = new Thread(count, "First");
Thread second = new Thread(count, "Second");
first.start();
second.start();
first.join();
second.join();
System.out. println("Loop count using Atomic Variables in Java: "+count.total);
}
}
Atomic Variables Output

You can also read about the Multiple Inheritance in Java.

Frequently Asked Questions

What is the atomic concept of Java?

The atomic concept in Java refers to operations that are indivisible and appear as if they occur instantaneously, ensuring thread safety without explicit synchronization.

What is atomic in multithreading?

In multithreading, atomic refers to operations that are performed atomically, without interference from other threads, ensuring thread safety.

Are the Atomic Variables in Java thread-safe?

Yes, Atomic Variables in Java are thread-safe. They ensure thread safety by providing atomic operations without the need for explicit synchronization mechanisms.

What are the most commonly used types of Atomic Variables in Java?

There are various types of Atomic Variables in Java, but some of the most commonly used Atomic Variables are,

  • AtomicInteger
  • AtomicBoolean
  • AtomicLong
  • AtomicReference

What package is associated with Atomic Variables in Java?

The Atomic Variable class can be imported into your Java code using the java.util.concurrent.atomic package.

Conclusion

This Blog covered all the necessary points about the Atomic Variables in Java. We further looked at examples to understand concurrency and Atomic Variables in Java.

Hey Ninjas! Don’t stop here. Check out Coding Ninjas for Python, more unique courses, and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems.

Thank You!!

Previous article
Lock frameworks vs. thread synchronization
Next article
Difference between Atomic, Volatile, and Synchronized
Live masterclass