Monday, February 12, 2018

Java Volatile Keyword and its use

This is the Second Tutorial of Multithreading Tutorials If you want to learn the basics of Multithreading you can read the previous post


So In Multithreading we use the Volatile keyword ,
What is Volatile Keyword and where we use it?
Volatile Keyword, the volatile modifier guarantees that any thread that reads a field will see the most recently written value.

We use volatile keyword when we don’t want the program to cache the variable in cpu rather thread will always read the value from the main memory.

Now let see the Program of Volatile keyword used in java.





Explanation :

In the above problem:
  • We have created a new thread which is checking the Boolean variable running , if variable value is true we are printing the Running on screen if it is false we are not printing.
  • If we have 2 thread and the variable is not volatile and one thread will check the variable value and see that the value is true and after one thread complete the task and change the value to false whereas the second thread is creating the variable value he is seeing it as true as the value is cached in the cpu and thread is only creating the cached value(This is happens sometime , not always) and it is seeing it as true but the current updated value is false . here we use the volatile keyword.
  • As using volatile keyword both the thread will always check the variable value from the main memory

NOTE: This problem only occurred  sometimes not always , but we need to cover all the scenario while coding.


When we are not using Volatile Keyword .





here the value will be cached in CPU Cache of Thread where the differences comes





When we use Volatile Keyword.

In this case the thread will directly read the value from the main memory only .


Is Volatile is Enough ??

As If there are 2 threads , both are reading and writing on shared resources then using the volatile keywords for that is not enough as we need to use synchronized in that case to guarantee that reading and writing both will be atomic. Or no 2 thread will have the access to write something on shared resource.
The volatile keyword is guaranteed to work on 32 bit and 64 variables.
We have a alternative of synchronization , we can use AtomicInteger  or AtomicBoolean which is a thread safe .

I hope this tutorial will help you in understand the volatile keyword and its use. In next tutorial we will post about the synchronization in java.

Thanks for Reading
Noeik


0 comments:

Post a Comment