双重锁定在单身人士 [英] Double Checked Locking in Singleton
问题描述
code> public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
//此类的私有属性
private String searchWord =;
private String [] list = new String [] {Stack,Overflow};
// private constructor
private SearchBox(){}
//静态方法获取实例
public static SearchBox getInstance(){
if(searchBox == null){//第一次锁
synchronized(SearchBox.class){
if(searchBox == null){//第二次锁
searchBox = new搜索盒();
}
}
}
return searchBox;
}
}
我仍然不太了解上面的代码。如果两个线程在实例为null时一起运行同一行代码,那么是什么问题?
if(searchBox == null) {
synchronized(SearchBox.class){
if(searchBox == null){
searchBox = new SearchBox();
}
}
}
出现时。两个线程都会看到object为null。然后两者同步。然后,他们再次检查,仍然看到它为空。并创建两个不同的对象。 OOOPS。
请为我解释。我理解错了什么?
感谢:)
不,因为你正在获得锁在 SearchBox.class
中,一次只能有一个线程进入同步块。所以第一个线程进入,然后找到 searchBox
并创建它,然后离开同步的块,然后第二个线程进入块,然后它发现 searchBox
不是空的,因为第一个线程已经创建了它,所以它不会创建一个新的实例 searchBox
双重检查模式用于避免每次执行代码时获取锁定,如果调用不在一起发生,那么第一个条件将失败,代码执行将不会执行锁定,从而节省资源。 p>
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 attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// 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;
}
}
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 ?
Thanks :)
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
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 everytime 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.
这篇关于双重锁定在单身人士的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!