Jyotirup Jyotirup - 4 months ago 26
Java Question

When to use volatile vs synchronization in multithreading in java?

When to use volatile keyword vs synchronization in multithreading?


Use volatile to guarantee that each read access to a variable will see the latest value written to that variable. Use synchronized whenever you need values to be stable for multiple instructions. (Note that this does not necessarily mean multiple statements; the single statement:

var++; // NOT thread safe!

is not thread-safe even if var is declared volatile. You need to do this:


See here for a nice summary of this issue.