Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Atomic
1.2.
Volatile
1.3.
Synchronized
2.
Atomic
2.1.
Example
3.
Volatile
3.1.
Example
4.
Synchronized
4.1.
Example 
5.
Difference between Atomic, Volatile, and Synchronized
6.
Frequently Asked Questions
7.
Key takeaways
Last Updated: Mar 27, 2024
Easy

Difference between Atomic, Volatile, and Synchronized

Author Shivam Verma
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Before knowing about the difference between Atomic, Volatile, and Synchronized, we have to know about these things.

Read More About, Basics of Java

Atomic

Atomic is a toolkit of variable java.util.concurrent.atomic package classes assist in writing lock and wait-free algorithms with the Java language. 

Volatile

Volatile is a keyword used to modify the value of a variable by different threads. It is also used to make class thread-safe.

Synchronized

Synchronized is a keyword used to define a block of code where multiple threads can safely access the same variable.

You can also read about the Multiple Inheritance in Java.

Atomic

  • Atomic variable guarantees that the operations made on the variable occur in an atomic manner.
  • Atomic variables are classes, and these classes come from the package java.util.concurrent.atomic. 
    Example: AtomicInteger, AtomicBoolean, AtomicLong, etc.

Example

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;
class Atomic_example implements Runnable
{
    private AtomicInteger count=new AtomicInteger();
    public void run()
    {
        for(int i=1;i<=5; i++)
        {
            try
            {
                Thread.sleep(i*50);
                count.getAndIncrement();
            }
            catch (InterruptedException ex)
            { 
                System.out.println(ex);
            }
        }
    }
    public int get_count()
    { 
        return count.get();
    }
}
public class Example
{
    public static void main(String[] args) throws InterruptedException
    {
        Atomic_example r=new Atomic_example();
        Thread th1 = new Thread(r);
        th1.start();
        Thread th2 = new Thread(r);
        th2.start();
        th1.join();
        th2.join();
        System.out.println("Count Value " + r.get_count());
    }
}

Output

Count Value 10

Also Read About, Multithreading in java

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

Volatile

  • Volatile is a keyword that is used to modify the value of a variable by different threads.
  • We can use the volatile keyword with variables. Using a volatile keyword with classes and methods is illegal.
  • When we have our variables as volatile, they are always visible to other threads.
  • If you declared the variable as volatile, Read and Writes are atomic.
  • We can use it as an alternative way of achieving synchronization in Java.

Example

import java.lang.*;
import java.io.*;
class volatile_example implements Runnable
{
    private static volatile boolean stopRequested;
    public void run()
    {
        int i=0;
        while(!stopRequested)
        {
            i++;
        }
        System.out.println("backgroundThread completed");
    }
    public void update()
    { 
        stopRequested=true;
    }


}
public class Example
{
    public static void main(String[] args) throws InterruptedException
    {
        volatile_example vo=new volatile_example();
        Thread bth= new Thread(vo);
        bth.start();
        Thread.sleep(1000);
        vo.update();
        System.out.println("Main completed");
    }
}

Output

Main completed
backgroundThread completed

 

Try it by yourself on java online compiler.

Synchronized

  • It allows only a single thread at a time to access the shared resource. It will not allow other threads and make the other threads wait for that accessing thread to release its access to the shared resource.
  • Each object in Java has a unique lock. So when a thread wants to execute a shared resource, it has to obtain the lock on that object, thereby avoiding other threads to access the same object.
  • It can be applied to methods and blocks. It actually occurs on the object. For any given single object, only one thread can execute a synchronized method/block at a time.

Example 

import java.util.*;
import java.lang.*;
import java.io.*;
class RaceCondition implements Runnable
{
    private int count;
    public void run()
    {
        for(int i=1;i<=5; i++)
        {
            try
            {
                Thread.sleep(i*50);
                count++;
            }
            catch (InterruptedException ex)
            { 
                System.out.println(ex);
            }
        }
    }
    public int get_count()
    { 
        return count;
    }
}
public class Example
{
    public static void main(String[] args) throws InterruptedException
    {
        RaceCondition r=new RaceCondition();
        Thread th1 = new Thread(r);
        th1.start();
        Thread th2 = new Thread(r);
        th2.start();
        th1.join();
        th2.join();
        System.out.println("Count Value " + r.get_count());
    }
}

Output

Count Value 10

 

Must Read Static Blocks In Java, Multithreading in Python

Difference between Atomic, Volatile, and Synchronized

Frequently Asked Questions

  1. What is the use of atomic in Java?
    Ans: The atomic classes are used to provide a lock-free and thread-safe environment or programming on a single variable. It also supports atomic operations.
     
  2. When can we use volatile variables in Java?
    Ans: We can use a volatile variable if we want to read and write long and double variables automatically.
     
  3. Can we make the array volatile in Java?
    Ans: Yes, We can make an array (both primitive and reference type array, e.g., an int array and String array) volatile in Java.
     
  4. Why do we need synchronization?
    Ans: The need for synchronization originates when processes need to execute concurrently. The main purpose of synchronization is to share resources without interference using mutual exclusion.

Key takeaways

In this article, we have extensively discussed the difference between Atomic, Volatile, and Synchronized in the java programming language. We also discussed Atomic, Volatile, and Synchronized keywords in Java with the help of an example.

Recommended Reading:

Difference Between C and Python

We hope that this blog has helped you enhance your knowledge regarding the difference between Atomic, Volatile, and Synchronized, and if you would like to learn more, check out our article on Multiple Inheritance in Java. You can start learning java basics from scratch with our guided path.

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Atomic Variables in Java
Next article
Date Class in Java
Live masterclass