Volatile keyword in Java
What is the use of volatile keyword in Java
In Java volatile keyword is used in a multithreading environment.Use of volatile keyword with variable guarantees that the value of that variable is read from main memory every time.
volatile keyword is used only with a variable.
What if we will not use the volatile keyword?
If we will not use volatile keyword then the thread will read the value from the CPU cache memory.
Let's take an example to understand this
public int counter = x;
Thread 1 is increasing the value of the counter 50 times.
Same time Thread 2 is also increasing the value of the counter by 50 times.
When Thread 1 increase the value and make it counter+1 then counter+2 but every time it is not going to read the value from memory but it will increase the cache value of the counter.So main memory will not have updated value of counter every time.
So when Thread 2 will start the task.It read the counter value which might not be the correct as the cached value from Thread 1 is not updated in main memory.
So here the problem is that both the thread will not get the latest value of the counter.Thus the use of volatile keyword with counter variable makes the counter value updated in main memory and thread read value from the main memory.All the reads and write of the counter variable will happen in main memory.
public volatile int counter = x;
volatile keyword is not enough
Do not get confused with using a volatile keyword in place of synchronization.When read and write is happening on same resources from multiple threads then thread synchronization is important to provide the resource access to one thread at a time.
Synchronization in Java - Synchronized keyword
Give your suggestion in comments.
If you like the post Share with your friends on social network.
Follow us: www.facebook.com/javainstance
Follow us: www.facebook.com/javainstance
Volatile keyword in Java
Reviewed by JavaInstance
on
12:21:00 PM
Rating:
Reviewed by JavaInstance
on
12:21:00 PM
Rating:

Thanks for sharing use of volatile keyword in here. You are running a great blog, keep up this good work.
ReplyDeleteAlso Read : AWS Training in chennai | AWS Training institute in velachery