Why is volatile used in singleton pattern

Why is volatile used in singleton pattern

八月 12, 2019

What is volatile

Volatile keyword is used to mark a variable as “being stored in main memory”. More precisely that means, that every read of a volatile variable will be read from the computer’s main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

Features

  • guarantees visibility of changes to variables across threads.
  • gives a “happens-before” guarantee
  • not guarantee atomic

Create a Singleton class without volatile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 public class Singleton {
2 private static Singleton instance;
3
4 private Singleton() {
5 }
6
7 public static Singleton getUniqueInstance() {
8 if (instance == null) {
9 synchronized (Singleton.class) {
10 if (instance == null) {
11 instance = new Singleton();
12 }
13 }
14 }
15 return instance;
16 }
17 }

The problem is that new operator is not atomic, it will cause some problem.If Thread A execute in 11 line, it try to assign a memory space to instance before it is finished all construct. Thread B execute in 8 line, the instance is not null and B try to use the instance, which has not be initialized. This results in Thread B failed to use instance because it try to use a partially constructed instance.