Home >Java >javaTutorial >Volatile Keyword in java
Volatile in java works like, if we want our object to be accessed by multiple threads simultaneously, we can use this keyword. This keyword is another way to make our class, code, method thread-safe that means multiple threads can access the same resource without any problem. We mean violating keyword indicates that we can say the multiple threads will manipulate that variable value simultaneously.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
If you want to make your code thread-safe, you can go for violates keyword. Also, it provides synchronization; in this case, it is a good choice.
Any variable that we are declaring using this keyword will not go to the cached; all the operations we perform, like reading and writing, will go to the main memory.
class DemoSharedObject { static int sharedresources = 10; }
Below one case which leads to data inconsistency:
We have one class named DemoSharedObject let’s assume that multiple threads are working on this class and going to modify the value of the class members. So if we have multiple threads running on the different processors, each of this thread has its own local copy resources. So if some thread modified the value of common resources, its value would not be reflected into the main memory very quickly. But in this case, our other threads do not know about the current value for the shared resources, so this will leads to a data inconsistency issue.
In java, we have two things synchronization statements and synchronization methods.
In this case, we just add the synchronized keyword to the method signature.
syntax:
public synchronized return_type method_name(){}
Example:
public class Demosynchronized { private int c = 0; public synchronized void method1() { c++; } public synchronized void method2() { c--; } public synchronized int method3() { return c; } }
In the above example, we are doing nothing but just increasing and decreasing the counter, but we have to introduce a synchronized keyword with the method so there will be no data inconsistency, and all threads will receive the updated value.
So when the first thread is doing its processing on the method1(), all other threads will get block (suspend); no other thread can access the same object until the working thread has already acquired the object’s lock. This is how they avoid inconsistency of data.
Also, there is now more thing that whenever the thread one completes its operation on the method1(), i.e. complete execution of a method, so it establishes o relationship with other thread so the changes in the object value or state are visible to other threads also.
syntax:
synchronized(){}
Example:
public void demo(String namestr) { synchronized(this) { lastName = namestr; count++; } list.add(namestr); }
In the above example, we have a synchronized block that is going to manage data for us. Like namestr is going to be synchronized by the demo() method. That means the data we want to synchronize; we just need to place them into this block only.
so when we have two thread which is writing and reading on the same object that means we have multiple threads which are accessing the same object for reading and writing purpose then we should go for violates keyword because it does not provide us with the guarantee of blocking of threads unless and until other threads stop there execution, so in this case, we should go for synchronization because it provides us with some more features over violate keyword like :
it can be used with the method as well as the block of statement that means we do not need to synchronize the whole method; we can write our code inside the block also, which we want to synchronize.
When we read or write the value of the volatile variable, they directly read or write the value to the main memory, which is not a good practice, and this is expensive as well in comparison to the cache. So think before you use volatile keywords; it will directly impact your performance.
Suppose we have multiple threads that are not depending upon each other’s response that means read and write are independent of each other to use the volatile keywords in this case. But we have one more case as well where it is not suitable to use the volatile keyword that is explained below :
Suppose thread has generated the first value of the volatile variable, and this current value will be used further to generate the new volatile variable values; in this case, this volatile keyword is not a good fit to generate the correct result; this condition will lead to a race condition were all thread going to read the same value but generate the new value for them and write the value to main memory and override each other values, so this will leads to the wrong result, or we can say data inconsistency issue, so here volatile keyword is not good enough to avoid this case we have to move to synchronization where we have to types to make our code synchronized, i.e. synchronized method and synchronized statement.
Code:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TvvApplication { private static final Logger LOGGER = LoggerFactory.getLogger(TvvApplication.class); private static final Object aclock = new Object(); private static final Object aclock1 = new Object(); private static volatile int MY_INT = 0; public static void main(String[] args) { System.out.println("without block"); System.out.println("with block calling static method :: "); testBlock(); } static void testBlock1() { synchronized (aclock1) { MY_INT = MY_INT + 1; System.out.println( Thread.currentThread().getName() +"new lock we create and printing voilatile value using block for block one:: "+ MY_INT); } } static void testBlock() { synchronized (aclock) { MY_INT = MY_INT + 1; System.out.println( Thread.currentThread().getName() +"new lock we create and printing voilatile value using block for block two:: "+ MY_INT); } } }
Output :
<img src="https://img.php.cn/upload/article/000/000/000/172500598784733.png" alt="Volatile Keyword in java" >
So this can provide thread safety when data does not depend on each other; if data depends, we should go for synchronization.
The above is the detailed content of Volatile Keyword in java. For more information, please follow other related articles on the PHP Chinese website!