Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Atomic vs Volatile vs Synchronized
Next article icon

Java Atomic vs Volatile vs Synchronized

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, multithreading can lead to challenges related to thread safety and data consistency. Java provides concurrency mechanisms like Atomic, Volatile, and Synchronized to address these issues and ensure thread safety. These mechanisms offer unique advantages and limitations.

Atomic vs Volatile vs Synchronized

Features

                     SynchronizedVolatileAtomic

Applies to

It applies to only blocks or methods.It applies to variables only.It is also applicable to variables only.

Purpose

It ensures mutual exclusion and data consistency by acquiring locks.It ensures the visibility of variables across threads but does not guarantee atomicityIt provides atomic operations on variables without needing locks

Performance

Performance is relatively low compared to volatile and atomic keywords because of the acquisition and release of the lock.Performance is relatively high compared to synchronized Keyword.Performance is relatively high compared to both volatile and synchronized keyword.

Concurrency

Because of its locking nature, it is not immune to concurrency hazards such as deadlock and livelock.Because of its non-locking nature, it is immune to concurrency hazards such as deadlock and livelock.Because of its non-locking nature, it is immune to concurrency hazards such as deadlock and livelock.

Synchronized Modifier

The synchronized keyword in Java is used to control access to shared resources among multiple threads. It can be applied to methods or blocks of code. When a method or block is declared as synchronized, only one thread can execute it on a given object at a time. This ensures data consistency and prevents race conditions.

Working of Synchronized Modifier:

  • It can be applied to methods or blocks of code.
  • When a method or block is synchronized, only one thread can execute it on a given object at any time.
  • Every object in Java has an intrinsic lock associated with it. A thread must acquire this lock before entering a synchronized method or block.
  • Synchronized code blocks may lead to thread contention, which can negatively impact performance, especially with excessive synchronization.

Example:

Java
// Java program to demonstrate  // the synchronized modifier import java.util.concurrent.TimeUnit;  class CounterThread extends Thread {     private int count;      // Synchronized method to prevent race conditions     @Override     public synchronized void run() {         try {             TimeUnit.MILLISECONDS.sleep(100);  // Simulate work with sleep         } catch (InterruptedException e) {             e.printStackTrace();         }         count++; // Increment the count     }      public int getCount() {         return count;     } }  public class Geeks {     public static void main(String[] args) throws InterruptedException {         CounterThread t1 = new CounterThread();         CounterThread t2 = new CounterThread();          t1.start();         t2.start();         t1.join();         t2.join();          // Expected output is 1 because only          // one thread can increment at a time         System.out.println("Count: " + t1.getCount());     } } 

Output
Count: 1 

Explanation: In the above example, the synchronized method ensures that only one thread can execute the run() method at a time, preventing race conditions. Though two threads attempting to increment the count concurrently, the synchronization ensures they are executed sequentially.

Volatile Modifier

The volatile keyword in Java ensures that all threads have a consistent view of a variable's value. It prevents caching of the variable's value by threads, ensuring that updates to the variable are immediately visible to other threads.

Working of Volatile Modifier:

  • It applies only to variables.
  • volatile guarantees visibility i.e. any write to a volatile variable is immediately visible to other threads.
  • It does not guarantee atomicity, meaning operations like count++ (read-modify-write operations) can still result in inconsistent values.

Example:

Java
// Java program to demonstrate the  // volatile modifier with non-atomic increment class Counter {     private volatile int count;   // Volatile variable      public void increment() {         count++;   // This operation is not atomic     }      public int getCount() {         return count;     } }  public class Geeks {     public static void main(String[] args) {         Counter c = new Counter();          Thread t1 = new Thread(() -> {             for (int i = 0; i < 1000; i++) {                 c.increment();             }         });          Thread t2 = new Thread(() -> {             for (int i = 0; i < 1000; i++) {                 c.increment();             }         });          t1.start();         t2.start();          try {             t1.join();             t2.join();         } catch (InterruptedException e) {             e.printStackTrace();         }           System.out.println("Count: " + c.getCount());     } } 

Output
Count: 2000 

Explanation: In the above example, the volatile variable is count. While volatile ensures visibility of changes across threads and the increament operation is non-atomic, race condition can still occur. The expected result may be less than or equal to 2000.

Atomic Modifier  

Atomic classes, such as AtomicInteger, are part of the java.util.concurrent.atomic package. These classes provide thread-safe operations on variables without the need for synchronization. They use low-level atomic operations like compare-and-swap (CAS) to ensure thread safety.

Working of Atomic Modifier:

  • Atomic operations ensure atomicity of the read-modify-write actions on variables.
  • These classes are lock-free and more efficient than synchronized blocks because they avoid the overhead of acquiring locks.
  • Atomic operations are performed using methods like incrementAndGet(), compareAndSet(), and getAndSet().

Example:

Java
import java.util.concurrent.atomic.AtomicInteger;  class CounterThread extends Thread {     private AtomicInteger count = new AtomicInteger();  // Atomic variable      @Override     public void run() {         for (int i = 0; i < 5; i++) {             try {                 Thread.sleep(i * 50);  // Simulate work with sleep                 count.incrementAndGet();  // Atomic increment operation             } catch (InterruptedException e) {                 e.printStackTrace();             }         }     }      public int getCount() {         return count.get();    // Get current value of count     } }  public class Geeks {     public static void main(String[] args)        throws InterruptedException {         CounterThread t1 = new CounterThread();         CounterThread t2 = new CounterThread();          t1.start();         t2.start();         t1.join();         t2.join();          // Expected output is 10 because          // each thread increments 5 times.         System.out.println("Count: " + (t1.getCount() + t2.getCount()));     } } 

Output
Count: 10 

Explanation: In the above example, the AtomicInteger class ensures that the incrementAndGet() operation is atomic across multiple threads. Each thread increments the count 5 times, so the final output will always be 10 (5 increments per thread). 


Next Article
Java Atomic vs Volatile vs Synchronized

M

mroshanmishra0072
Improve
Article Tags :
  • Java
  • Difference Between
  • Java-keyword
Practice Tags :
  • Java

Similar Reads

    volatile Keyword in Java
    Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example.  class SharedObj { // Changes made to sharedVar in on
    5 min read
    Java Lock Framework vs Thread Synchronization
    In Java, thread synchronization is achieved using the Lock framework which is present in the java.util.concurrent package. Synchronization ensures that only one thread can access a resource at a time by preventing issues like data corruption or inconsistency. Java offers two primary mechanisms for a
    4 min read
    Scoped Values in Java
    In Java, Scoped variables enable the exchange of immutable data across and between threads. This new API is implemented as an incubator preview feature in Java 20 as part of JEP 439. They are preferred over thread-local variables, especially when a large number of virtual threads are used. This is a
    4 min read
    Synchronization of ArrayList in Java
    Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally. Structural modification implies the addition or deletion of element(s) from the list or explicitly resizes the ba
    4 min read
    Java Method and Block Synchronization
    In Java, Synchronization is very important in concurrent programming when multiple threads need to access shared resources. Java Synchronization can be applied to methods and blocks. Method synchronization in Java locks the entire method and Block synchronization locks only a specific section of the
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences