Jyotirup Jyotirup - 17 days ago 7
Java Question

When to use volatile vs synchronization in multithreading in java?

When to use volatile keyword vs synchronization in multithreading?

Answer

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:

synchronized(LOCK_OBJECT){var++;}

See here for a nice summary of this issue.

Comments