---
title: "答复: 关于同步访问，双重检查问题"
author: "wyuch"
date: "2012-10-29T19:09:51Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-29T19:09:51Z"
id: 1707689
url: "https://wyuch.iteye.com/blog/1707689"
---

楼主的代码没有问题，所谓的双重锁定问题，是因为JAVA内存模型的无序写入缺陷导致的，在一部分JVM上存在这样的情况：


```java

public static Singleton getInstance()
 {
   if (instance == null)
   {
     synchronized(Singleton.class) {  //1
       if (instance == null)          //2
         instance = new Singleton();  //3
     }
   }
   return instance;
 }
 
```


上述代码可能会导致双重锁定失败。这是因为在//3处，在部分JVM中，instance会在new Singleton()执行之前就被置为非null了，从而导致双重锁定失败。具体请参见
http://www.ibm.com/developerworks/cn/java/j-dcl.html

但在你的例子中，没有类似静态变量instance的东西，resource是从map中取出来的，不存在无序写入的问题，不可能会锁定失败。

至于性能，因为大部分调用不会进入第一个 if (resource == null) ，所以问题不大。