问题描述
这是我的单例模式自定义类.在这段代码中,我使用如下双重检查锁定.当我在某些来源上阅读了许多帖子时,他们说双重检查很有用,因为它可以防止同时运行的两个并发线程生成两个不同的对象.
here is my custom class for singleton pattern. in this code, I use double-checked locking as below. As I read many posts on some source, they say that double check is useful because it prevents two concurrent threads run at same times make two different objects.
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
我还是不太明白上面的代码.有什么问题,如果实例为 null 时两个线程一起运行同一行代码?
I still don't understand above code so much. What is the problem, if two threads together run same line of code when instance is null ?
if (searchBox == null) {
synchronized (SearchBox.class) {
if (searchBox == null) {
searchBox = new SearchBox();
}
}
}
出现时.两个线程都会看到对象为空.然后两者同步.然后,他们再次检查,仍然看到它为空.并创建两个不同的对象.哎呀.
When that appear. both two threads will see object is null. then both synchronize. and then, they check again, and still see it null. and create two different objects. OOOPS.
请给我解释一下.我理解错了什么?
Please explain for me. What have I understand wrong ?
谢谢:)
推荐答案
否,由于您正在获取 SearchBox.class
的锁,因此一次只有一个线程会进入同步块.所以第一个线程进入然后发现searchBox
为空并创建它然后离开同步块,然后第二个线程进入块然后发现searchBox
不为空因为第一个线程已经创建了它,所以它不会创建 searchBox
的新实例.
No, since you are obtaining lock on the SearchBox.class
, only one thread will enter the synchronized block at a time. So the first thread enters then finds searchBox
is null and creates it and then leaves the synchronized block, then the second thread enter the block then it finds that the searchBox
is not null because the first thread already created it so it will not create a new instance of searchBox
.
双重检查模式用于避免每次执行代码时都获取锁.如果调用没有同时发生,则第一个条件将失败,代码执行将不会执行锁定,从而节省资源.
The double checked pattern is used to avoid obtaining the lock every time the code is executed. If the call are not happening together then the first condition will fail and the code execution will not execute the locking thus saving resources.
这篇关于单例中的双重检查锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!