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,
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.
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); } }
You can also try this code with Online Java Compiler
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,
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); } }
You can also try this code with Online Java Compiler
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.
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); } }
You can also try this code with Online Java Compiler
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.