Home >Java >javaTutorial >How to solve the double check lock problem in java

How to solve the double check lock problem in java

PHPz
PHPzforward
2023-04-18 11:31:041687browse

The origin of double check lock

First let’s take a look at the non-thread-safe initialization singleton mode

	public class UnsafeLazyInitialization {
		private static UnsafeLazyInitialization instance;

		public static UnsafeLazyInitialization getInstance(){
			if(instance == null){                           //1:  线程A执行
				instance = new UnsafeLazyInitialization();  //2: 线程B执行
			}
			return instance;
		}
	}

In the UnsafeLazyInitialization class, assume that when thread A executes code 1, thread B When code 2 is executed, thread A may see that the instance reference object has not yet been initialized.

For the UnsafeLazyInitialization class, we can synchronize the getInstance() method to achieve thread-safe delayed initialization. The sample code is as follows:

	public static synchronized  UnsafeLazyInitialization getInstance(){
			if(instance == null){                           //1:  线程A执行
				instance = new UnsafeLazyInitialization();  //2: 线程B执行
			}
			return instance;
		}
	}

Because the above code does the getInstance() method Without synchronization processing, this may lead to increased synchronization program overhead. If getInstance() is frequently called by multiple threads, the program execution performance will be reduced. On the contrary, if it is not called by multiple threads, the delayed initialization method of the getInstance() method will affect performance.

Before JVM 1.6, synchronized was a heavyweight lock, so it was very performance-consuming, so people thought of a double-check locking (Dobule-check Locking) solution to improve performance. The sample code is as follows:

	public class DoubleCheckedLocking {                                 //1、
		private static Instance instance;                               //2、
		public static Instance getInstance(){                          //3、
			if(instance == null){                                      //4、第一次检查
				synchronized (DoubleCheckedLocking.class){              //5、枷锁
					if(instance == null){                                //6、第二次检查
						instance = new Instance();                       //7、问题的根源在这里
					}                                                    //8、
				}
			}
			return instance;
		}
	}

As shown in the above code: If the first check instance in step 4 is not null, there is no need to perform the following locking operation, which greatly reduces the performance problems caused by synchronized locks. There seems to be no problem with the above code. 1. When multiple thread views create new objects, the synchronized keyword can be used to ensure that only one thread successfully creates the object.

2. If the instance object has been created, obtain the object instance directly through the getInstatnce() method.

Double verification lock problem above

The above code looks perfect, but when step 4 is executed, instatnce! =null, the reference object of instatnce may not be initialized yet.

The root of the problem

When we execute the above code to step 7, instance = new Instance();, an object is created. The steps to create an object can be divided into three steps, as follows :

	memory = allocate()  //1.分配内存空间memory
	ctorInstance(memory) //2, 初始化对象在内存 分配内存空间memory上初始化 Singleton 对象
	instance = memory //3、设置 instance 指向刚分配的内存地址memory

The above three lines of code 2 and 3 may be reordered. (On the JTI compiler, this reordering really happens) The execution sequence after the reordering of steps 2 and 3

	memory = allocate()  //1.分配内存空间memory
	instance = memory //3、设置 instance 指向刚分配的内存地址memory
									// 注意此时instance对象还没有被初始化,但是instance的引用已经不是null了。
	ctorInstance(memory) //2, 初始化对象在内存 分配内存空间memory上初始化 Singleton 对象

Let’s take a look at the multi-thread execution sequence

How to solve the double check lock problem in java

How to solve the double check lock problem in java

##Line 7 of the above code instance = new Instance(); If thread A If instruction reordering (2,3) occurs, then another thread B may determine that instance is not empty in line 4 of code. Thread B next accesses the reference object of instance, but the instance object may not have been initialized by A. At this time, thread B may access an object that has not been initialized, resulting in a null pointer error.

Problem Solution

1. Instructions 2 and 3 are not allowed to be rearranged. 2. Allow 2 and 3 to be reordered, but do not allow other threads to see the reordering

volatile-based solution

Based on the above code, you only need to add the volatile keyword to the instance statement That’s it, the following code

	public class DoubleCheckedLocking {                                 //1、
		private static volatile Instance instance;                               //2、
		public static Instance getInstance(){                          //3、
			if(instance == null){                                      //4、第一次检查
				synchronized (DoubleCheckedLocking.class){              //5、枷锁
					if(instance == null){                                //6、第二次检查
						instance = new Instance();                       //7、问题的根源在这里
					}                                                    //8、
				}
			}
			return instance;
		}
	}

The above is the detailed content of How to solve the double check lock problem in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete