--It's a modifier given to variables. In some cases it can be used instead of synchronized. --The following is a usage example.
private static volatile int count = 0;
--If multithreading is used, each thread may cache the value of the field. Role to exclude from this cache (Since each thread prepares a copy of the variable for performance improvement, if the value in the main memory changes, it may deviate from the value in the thread) --If you add volatile, you can request ** read this variable from main memory **.
--When Java is compiled, optimization is performed to eliminate unnecessary evaluation.
#The code below...
boolean flg = true;
while(flg){
System.out.println("hello!");
}
#Optimized as follows...→ The loop does not end on the assumption that flg is changed to false in another thread!
if(flg){
while(true){
System.out.println("hello!");
}
}
--By adding volatile, you can request that you do not perform the above ** optimization **.
--Synchronized is more sophisticated (volatile is a simplified version of synchronized) --volatile has the above role, but it is not thread-safe. --volatile has the role of synchronizing variables between the thread and main memory (= reading the value from main memory without caching), but synchronized also has the role of performing exclusive control. -It is wrong to say that ** volatile ** can be used for exclusive control.
[Difference Between Volatile and Synchronized Keywords in Java] https://dzone.com/articles/difference-between-volatile-and-synchronized-keywo
Recommended Posts