Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile used in double checked locking

From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:

public class Singleton {     private volatile static Singleton instance;     private Singleton() {}     public static Singleton getInstance() {         if (instance == null) {             synchronized (Singleton.class) {                 if (instance == null) {                     instance = new Singleton();                 }             }         }         return instance;     } } 

I don't understand why volatile is being used. Doesn't volatile usage defeat the purpose of using double checked locking i.e performance?

like image 737
toc777 Avatar asked Oct 21 '11 21:10

toc777


People also ask

Why volatile is used in singleton?

The volatile prevents memory writes from being re-ordered, making it impossible for other threads to read uninitialized fields of your singleton through the singleton's pointer.

Why double-checked locking is broken?

Although the double-checked locking idiom cannot be used for references to objects, it can work for 32-bit primitive values (e.g., int's or float's). Note that it does not work for long's or double's, since unsynchronized reads/writes of 64-bit primitives are not guaranteed to be atomic.

What is a double lock and why it is used?

In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock.

How does volatile work in Java?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.


1 Answers

A good resource for understanding why volatile is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well.

The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

like image 79
Tim Bender Avatar answered Oct 19 '22 09:10

Tim Bender