I am trying to understand how multithreading works in Java. I understand the difference between Volatile
and Synchronization
.
Volatile
is about visibility and doesn't guarantee synchronization. When we are working with multithreading environments, each thread creates its own copy on a local cache of the variable they are dealing with. When this value is being updated, the update happens first in the local cache copy, and not in the real variable. Therefore, other threads are agnostic about the values that other threads are changing. And this is where volatile
comes into picture. Volatile fields are immediately written through to main memory, and reads occur from main memory.
Snippet from Thinking In Java
-
Synchronization also causes flushing to main memory, so if a field is completely guarded by synchronized methods or blocks, it is not necessary to make it volatile.
It’s typically only safe to use volatile instead of synchronized if the class has only one mutable field. Again, your first choice should be to use the synchronized keyword—that’s the safest approach, and trying to do anything else is risky.
But my question is, if in a synchronized block, a non volatile shared variable is being modified, will the other threads see the updated data ? (Since the variable in question is non volatile, other threads should read stale data from cache instead of main main memory)
If the answer to the above question is NO
, then can I conclude that everytime I use synchronization, I should ensure that shared variables must be marked volatile
?
And if the answer is YES
, then does that mean that I can always use synchronization
instead of marking shared variables are volatile
?
p.s: Before asking this question, I have read through lot of answers on StackOverflow and on other sites, but I couldn't find the answer to my question.
volatile
if you're only accessing it through asynchronized
block. The answers in that question address that. – Hypothesis