From f620065c81169d5c036fb5f546c5faa58018a875 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Apr 2018 22:37:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=95=E4=BE=8B=E6=A8=A1=E5=BC=8F=20volatile?= =?UTF-8?q?=20=E7=9A=84=E4=BD=9C=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/设计模式.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/notes/设计模式.md b/notes/设计模式.md index fd0f6ee4..a6008027 100644 --- a/notes/设计模式.md +++ b/notes/设计模式.md @@ -126,6 +126,19 @@ if (uniqueInstance == null) { } ``` + +uniqueInstance 采用 volatile 关键字修饰也是很有必要的。 + +`uniqueInstance = new Singleton();` 这段代码其实是分为三步执行。 + +1. 分配内存空间。 +2. 初始化对象。 +3. 将 uniqueInstance 指向分配的内存地址。 + +但是由于 JVM 具有指令重排的特性,有可能执行顺序变为了 `1>3>2`,这在单线程情况下自然是没有问题。但如果是多线程就有可能 B 线程获得是一个还没有被初始化的对象以致于程序出错。 + +所以使用 volatile 修饰的目的是禁止 JVM 的指令重排,保证在多线程环境下也能正常运行。 + # 三、简单工厂 ## 意图