Jyotirup Jyotirup - 1 year ago 74
Java Question

When to use volatile vs synchronization in multithreading in java?

When to use volatile keyword vs synchronization in multithreading?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download