The Wayback Machine - https://web.archive.org/web/20240926111827/https://www.geeksforgeeks.org/difference-between-atomic-volatile-and-synchronized-in-java/
Open In App

Difference Between Atomic, Volatile and Synchronized in Java

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes. There may be a chance of data inconsistency problem to overcome this problem we should go for a synchronized keyword when multiple threads are trying to operate simultaneously on the same java object. If a method or block declares as synchronized then at a time only one thread at a time is allowed to execute that method or block on the given object so that the data inconsistence problem will be resolved. The main advantage of synchronized keywords is we can resolve data inconsistence problems but the main disadvantage of this keyword is it increases the waiting time of the thread and creates performance problems. Hence, It is not recommended using, the synchronized keyword when there is no specific requirement. Every object in java has a unique lock. The lock concept will come into the picture when we are using a synchronized keyword. 

The remaining threads are not allowed to execute any synchronized method simultaneously on the same object when a thread executing a synchronized method on the given object. But remaining threads are allowed to execute the non-synchronized method simultaneously.

Volatile Modifier:

Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory. However, the use of volatile is limited to a very restricted set of cases as most of the times atomicity is desired. For example, a simple increment statement such as x = x + 1; or x++ seems to be a single operation but is really a compound read-modify-write sequence of operations that must execute atomically.

Atomic Modifier:  

If a value of a variable keeps on changing by multiple threads then there may be a chance of a data inconsistency problem. We can solve this problem by using an atomic variable. Data inconsistency problem can be solved when objects of these classes represent the atomic variable of int, long, boolean, and object reference respectively.

Example:

In the below example every thread increments the count variable 5 times. So after the execution of two threads, the finish count value should be 10.

Java
// import required packages
import java.io.*;
import java.util.*;

// creating a thread by extending a thread class
class myThread extends Thread {
  
    // declaring a count variable
    private int count;

    public void run()
    {
        // calculating the count
        for (int i = 1; i <= 5; i++) {

            try {
                Thread.sleep(i * 100);
                count++;
            }
            catch (InterruptedException
                       e) { // throwing an exception
                System.out.println(e);
            }
        }
    }
    // returning the count value
    public int getCount() { return this.count; }
}
// driver class
public class GFG {
  
    // main method
    public static void main(String[] args)
        throws InterruptedException
    {

        // creating an thread object
        myThread t = new myThread();
        Thread t1 = new Thread(t, "t1");
      
        // starting thread t1
        t1.start();
        Thread t2 = new Thread(t, "t2");
      
        // starting thread t2
        t2.start();
      
        // calling join method on thread t1
        t1.join();
      
        // calling join method on thread t1
        t2.join();
      
        // displaying the count
        System.out.println("count=" + t.getCount());
    }
}

 
 


Output
count=10

If we run the above program, we will notice that the count value varies between 6,7,8.9 The reason is that count++ is not an atomic operation. So by the time one thread read it’s value and increment it by one, another thread has read the older value leading to the wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic.


Below program will always output count value as 8 because AtomicInteger method incrementAndGet() atomically increments the current value by one. 

Java
// import required packages
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

// creating a thread by extending a thread class
class myThread extends Thread {
  
    // declaring an atomic variable
    private AtomicInteger count = new AtomicInteger();

    public void run()
    {
        // calculating the count
        for (int i = 1; i <= 5; i++) {
            try {
              
                // putting  thread on sleep
                Thread.sleep(i * 100);
              
                // calling incrementAndGet() method
                // on count variable
                count.incrementAndGet();
            }
            catch (InterruptedException e) {
              
                // throwing exception
                System.out.println(e);
            }
        }
    }
    // returning the count value
    public AtomicInteger getCount() { return count; }
}
// driver class
public class GFG {
  
    // main method
    public static void main(String[] args)
        throws InterruptedException
    {
        // creating an thread object
        myThread t = new myThread();
      
        Thread t1 = new Thread(t, "t1");
      
        // starting thread t1
        t1.start();
      
        Thread t2 = new Thread(t, "t2");
      
        // starting thread t2
        t2.start();
      
        // calling join method on thread t1
        t1.join();
      
        // calling join method on thread t1
        t2.join();
      
        // displaying the count
        System.out.println("count=" + t.getCount());
    }
}

 
 


Output
count=10
                     Synchronized                      Volatile                 Atomic
1.It is applicable to only blocks or methods.1.It is applicable to variables only.1.It is also applicable to variables only.
2. Synchronized modifier is used to implement a lock-based concurrent algorithm, and i.e it suffers from the limitation of locking.2.Whereas Volatile gives the power to implement a non-blocking algorithm that is more scalable.2.Atomic also gives the power to implement the non-blocking algorithm.
3.Performance is relatively low compare to volatile and atomic keywords because of the acquisition and release of the lock.3.Performance is relatively high compare to synchronized keyword.3.Performance is relatively high compare to both volatile and synchronized keyword.
4.Because of its locking nature it is not immune to concurrency hazards such as deadlock and livelock.4.Because of its non-locking nature it is immune to concurrency hazards such as deadlock and livelock.4.Because of its non-locking nature it is immune to concurrency hazards such as deadlock and livelock.


 



Previous Article
Next Article

Similar Reads

Difference between Volatile Memory and Non-Volatile Memory
Memory is one of the most fundamental components in computing systems. Broadly, computer memory can be divided into two types namely volatile memory and non volatile memory. Even though both are crucial in the total functioning of the electronics, they are not interchangeable, each playing specific roles. Volatile memory deploys power in order to s
6 min read
Atomic Mass and Atomic Number
Atomic Mass and Atomic Number are somewhat similar concepts in chemistry. Atomic Number tells us about the number of electrons or protons, whereas Atomic Mass tells us about the number of neutrons and protons combined. These two parameters are important in learning about atoms and their various properties. This article explores these two concepts b
7 min read
Difference Between Hashtable and Synchronized Map in Java
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and also the equals method. Features of Hashtable: It is kind of like HashMap but is synchronized.Has
3 min read
Difference Between ConcurrentHashMap, HashTable and Synchronized Map in Java
Here we will be discussing out one by one individually then rolling onto the difference after having an adequate understanding of all three of them. We will be discussing ConcurrentHashMap first followed by HashTable, lastly followed by Synchronized Map. Let us start with ConcurrentHashMap first. The underlying data structure for ConcurrentHashMap
6 min read
Difference between volatile and transient keywords in Java
Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. Before getting into the differences, let us first understand what each of them actually means. Volatile: The Volatile keyword is used to mark the
3 min read
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 one thread // may not immediately reflect in other th
5 min read
Difference Between Atomic and Molecular Elements
Difference Between Atomic and Molecular Elements: Elements are the basic substances that make up all matter in chemistry. They are divided into two groups: atomic elements and molecular elements. An atomic element is a chemical element that naturally exists as individual atoms, meaning it's not bound to other atoms of the same element. On the other
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this article, the difference between these two IO pack
3 min read
Difference between Java and Core Java
Java is a very famous language that is based on the object-oriented programming concepts. It is the successor of the C and C++ languages. It was developed by Sun Microsystems. Core Java is a term used by Sun Microsystems to refer to the Java to standard edition J2SE. This is the parent of all other editions of Java used on internet sites. It has a
2 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with examples and also the difference between these two packag
2 min read
Difference between Core Java and Advanced Java
Java is a versatile and widely used programming language that helps in the development of many software applications. It is popular for its portability, robustness, and ease of use, making it a preferred choice for both beginners and experienced developers. Java's ecosystem can be largely categorized into two main parts that are Core Java and Advan
4 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
6 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Difference between Difference Engine and Analytical Engine
Introduction: The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some sim
7 min read
Difference between Voltage Drop and Potential Difference
Voltage Drop is defined as the decrease in the electric potential along the path of current that is flowing in an electric circuit. Voltage drop can be assigned at each point in the electric circuit that is proportional to the electrical elevation. The amount of energy delivered per second to any component in the circuit is equal to the voltage dro
4 min read
Difference Between Electric Potential and Potential Difference
The flow of electric charges is known as electricity, and it is responsible for producing electric current. An important word associated with electricity is electric potential. A potential difference is required to create the flow of electrons and hence, produce electricity. Before understanding the difference between electric potential and potenti
7 min read
Difference Between Length and Capacity in Java
Length and capacity are two different things in Java. Length basically increases when characters are appended to the string whereas the capacity increases when the current capacity is exceeded by a new length. length () method is a part of the Java String class. It is used to find the length of the string. It basically counts the number of characte
3 min read
Difference Between throw and throws in Java
Prerequisite: Throw and Throws in Java The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method. The differences between throw and throws in Java are: S. No. Key Difference throw thro
2 min read
Difference between Traditional Collections and Concurrent Collections in java
We all know about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like: Most of the Classes which are present in Traditional Collections (i.e ArrayList, L
3 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Difference Between LinkedList and LinkedHashSet in Java
In this article you will learn difference between LinkedList and LinkedHashSet in java. Prerequisite: LinkedList : LinkedHashSet LinkedList class implements the List and Deque interface and extends from AbstractSequentialList class. LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. Java Linked
3 min read
Difference between length of Array and size of ArrayList in Java
Array has length property which provides the length of the Array or Array object. It is the total space allocated in memory during the initialization of the array. Array is static so when we create an array of size n then n blocks are created of array type and JVM initializes every block by default value. Let's see this in the following figure. On
2 min read
Difference between ArrayList and HashSet in Java
Here are couple of differences between ArrayList and HashSet. Inheritance: Implementation: Implementation : ArrayList implements List interface while HashSet implements Set interface in Java.Internal implementation: ArrayList is backed by an Array while HashSet is backed by an HashMap.Duplicates : ArrayList allows duplicate values while HashSet doe
3 min read
What is the difference between field, variable, attribute, and property in Java
Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some p
2 min read
Difference Between Daemon Threads and User Threads In Java
In Java, there are two types of threads: Daemon ThreadUser Thread Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks. Differ
4 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Difference Between ArrayList and HashMap in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java's collection since Java 1.2. It provides the basic implementation o
7 min read
Difference between Java and C language
Here are some of the differences between Java and C language. C is much faster than Java Java is slower than C due to overhead. C Java C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.C is a Procedural Programming Language.Java is Object-Oriented language.C is more procedure-oriented.Java is mor
3 min read
Practice Tags :