Aditya W Aditya W - 5 months ago 23
Java Question

volatile + synchronized combination in multithreaded scenario

I have good knowledge of

synchronization
internals and basic knowledge of
volatile
internals.

I have one query, which is follow-up to below SE question:

Why is volatile used in this example of double checked locking

I'm confused about one part. If I strictly follow above example, I have to add
volatile
to many variables but I am sure that all multi-threaded applications are not using this volatile + synchronized combination.

If
synchronization
is not guaranteeing memory consistency as per above example, what are the use cases of using combination of
volatile
variables with
synchronization
code?

Answer

When a variable is defined volatile it is read from the main memory instead of registries.

So each processor will see the same value.

In the double check the variable is defined as volatile to be sure to check outside of synchronized block will intercept most of cases.

If the variable is not volatile the code will work, but if you have more processors you can go inside of the synchronized block more than needed (also when the variable is not null).

If all access to a variable are done in the synchronized block a volatile is not necessary at all.

Comments