Aquarius_Girl
Aquarius_Girl

Reputation: 22946

Do we need volatile keyword and the mutex locks together for thread safety?

Having mutex locks for critical section says that more than one thread won't be able to ruin the critical section, but then why would we need the volatile variable for the same thing?

What would happen if there is no volatile word in the following code?

enter image description here

Upvotes: 1

Views: 632

Answers (2)

Malcolm Smith
Malcolm Smith

Reputation: 3580

The volatile keyword makes the double checked locking work correctly on 1.5 and later JVMs, see the Under the new Java Memory Model section of that page.

If there was no volatile keyword there is a possibility of two instances being created on 1.5 and later JVMs. On pre-1.5 JVMs double checked locking is considered completely broken, and should not be used.

However, in the case of initialising a singleton, the use of double checked locking is usually considered not worth it and a simple static initialisation will suffice. If you absolutely know the singleton will be initialised at some point by your application, then the lazy instantiation is redundant. Just go for:

private static Singleton s_instance = new Singleton() 

or whatever the C++ equivalent is. Nice and safe!

As this question has ended up a rather tangled mess of Java & C++ please note, I am referring to Java above. In C++ there is no synchronized keyword, and volatile is not applicable to concurrency.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273721

The volatile keyword does not provide any locking.

Its purpose is to prevent compiler optimizations that would 'cache' the value so that a thread might be checking out-of-date data.

Volatile is subtly different between languages and always a bit of a problem. Read your specs carefully and follow trusted examples.

Upvotes: 3

Related Questions