Difference Between Synchronized and Volatile in Java

volatile
Reading Time: 3 minutes

Even though synchronized and volatile help to keep away from multi-threading issues, they’re completely unique from each other. Before seeing the difference between them, let’s understand what does synchronized and volatile variables in Java provide.

Synchronization in Java

We all know that Java is a multi-threaded language in which multiple threads execute in parallel to complete program execution, so in this multi-threaded environment synchronization of Java objects become very important.
And the way through which we can achieve synchronization in java is by using two keywords “synchronized” and “volatile”.

The synchronized modifier is only for methods and blocks not for variables and classes. Synchronized keyword comes into the picture when multiple threads are trying to get access to the same java object simultaneously. A synchronized block or method allows only one thread at a time to execute on a given object, which will solve the problem of data inconsistency.
To use synchronized keywords in Java we have two ways 1) Synchronized method 2) Synchronized block

Synchronized Method

If we are using a synchronized keyword with a method then it will allow only one thread at a time to let its task complete. If multiple threads try to access a method, then the thread that would come first will get the lock and perform its execution. And the rest of the thread will wait for the first thread to finish its execution

public class Counter {

   private static int count = 0;

   public static synchronized int getCount() {
      return count;
   }

   public synchronized setCount(int count) {
      this.count = count;
   }

}

Synchronized Block

If we are using a synchronized keyword with a block then it will also allow only one thread at a time to let its task complete. Synchronized block has limited scope than synchronized method.

public class Singleton {

   private static volatile Singleton _instance;

   public static Singleton getInstance() {
      if (_instance == null) {
         synchronized(Singleton.class) {
            if (_instance == null)
               _instance = new Singleton();
         }
      }
      return _instance;
   }
}

Key Differences

  • A synchronized method assigns an object-level or class-level corresponding lock. And synchronized block assign a lock to the object based on the parameter.
  • A synchronized method lock on the entire functionality of the method concerned. And a synchronized block is used to acquire the lock on a small number of the consecutive statement. (i.e Critical section area)

Volatile keyword in Java

A volatile keyword is a field modifier that provides a visibility guarantee. Java uses volatile as an indicator to the Java compiler and thread that does not cache the value of this variable and always reads it from the main memory. The volatile keyword is only used with variables not with methods or classes.

Example:-

class Test
{
boolean flag = true;
}

In the above example, suppose two threads are working on the same class. Both threads run on different processors where each thread has its local copy of the flag. And if any thread changes the value of the flag, in the main memory the value will not get reflected and because the other threads are not aware of the changed value it will lead to data inconsistency.

class Test
{
volatile boolean flag = true;
}

In the above example, we have declared the flag as volatile so that the value of the variable will never be stored in the cache. And all the read and write operations will be done from and to the main memory.

Differences

Synchronized Volatile
Synchronized is applicable only on blocks or methods.Volatile is applicable to variables only.
The synchronized modifier is used to implement a lock-based concurrent algorithm, i.e it suffers from the limitation of locking.Whereas Volatile gives the power to implement a non-blocking algorithm that is more scalable.
The performance is relatively low compared to the volatile and atomic keywords due to the acquisition and release of the lock.The performance is relatively higher than that of the synchronized keyword.
Variables used inside the synchronized method or block are cached. Volatile variables are not cached.

Conclusion

In this blog, we have learned about the difference between synchronized and volatile keywords in java and also about the synchronized method and synchronized block. For more blogs click here
Hope you enjoyed the blog. Thanks for reading.

References

https://dzone.com/articles/difference-between-volatile-and-synchronized-keywo

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading