Aditya W Aditya W - 1 year ago 66
Java Question

volatile + synchronized combination in multithreaded scenario

I have good knowledge of

internals and basic knowledge of

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
to many variables but I am sure that all multi-threaded applications are not using this volatile + synchronized combination.

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

Answer Source

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.