Q31: What is a Volatile variable?
Ans: If you are using “volatile” keyword for a variable than Java guarantees every change on volatile variable will be visible to other thread. It will always read a variable value from “Main memory” and never from CPU Cache and Registers. Similarly every write will also be done in “Main memory”. In one line: volatile variables read and write always happen from Main memory.
If thread is doing any operation on a volatile variable, it will always read from main memory and copy it in CPU cache than process the variable. Once processing is done immediately flush back from CPU cache to main memory (It always update main memory, so other thread will read from main memory , latest value).
Q32. What all guarantees java volatile variable?
Ans: “volatile variable” gives below guarantee
- Let’s assume there are two threads ThreadA and ThreadB. If ThreadsA start writing to volatile variable and has few other variables in memory and at the same time ThreadB reads the same volatile variable. Then all variables which were visible to ThreadA before writing the volatile variable, same variable will be visible to ThreadB after reading “volatile variable”
- Instruction reordering: For performance reason JVM re-order instructions). So before and after of volatile variable instructions may re-order, but volatile read and write instructions can not be re-ordered.
int count1=0; int count2=0; int count3=0; volatile count4=0; int coount5=0; int count6=0; int count7=0; |
JVM can re-order count1 to count3 only if writing happens before writing count4 variable. Similarly JVM can re-order count5 to count7 only if writing happens before count4.
Suppose thread writes count4 from CPU cache to main memory and it also has other variable like count1 to count3 and count5 to count7 in memory, then it will also flush these variables to main memory.
Q33. Is volatile guarantees 100% visibility?
Ans: Because there is no lock involved. Hence, small time gap while reading and writing back to main memory can lead to “Race condition”.
Q34. When is volatile good to use?
Ans: If only one thread is writing and all other threads just need to read the variable. Hence, all the reading thread will always read the latest value written to main memory, and they are not going to change the value, hence no “Race condition”
Q35. Does volatile impact the overall performance?
Ans: Yes, because reading from main memory and writing to main memory is always expensive than reading and writing from CPU cache or registers.