Double check locking and delayed initialization, lock delay Initialization

Source: Internet
Author: User

Double check locking and delayed initialization, lock delay Initialization

In Java programs, it is sometimes necessary to postpone some highly-open object initialization operations, and only initialize these objects when they are used. In this case, programmers may adopt delayed initialization. However, some skills are required to correctly implement thread-safe delayed initialization. Otherwise, problems may occur easily. For example, the following is a sample code for non-thread-safe delayed initialization objects:

Public class UnsafeLazyInitialization {private static Instance instance; public static Instance getInstance () {if (instance = null) // 1: thread A executes instance = new Instance (); // 2: Line B executes return instance ;}}

In UnsafeLazyInitialization, assume that thread B executes code 2 while thread A executes code 1. At this point, thread A may see that the object referenced by the instance has not been initialized (for the reason of this situation, see the "root cause of the problem" in the following article ").

For UnsafeLazyInitialization, We can synchronize getInstance () to implement thread-safe delayed initialization. The sample code is as follows:

public class SafeLazyInitialization {    private static Instance instance;    public synchronized static Instance getInstance() {        if (instance == null)            instance = new Instance();        return instance;    }}

Synchronized causes performance overhead because getInstance () is synchronized. If getInstance () is frequently called by multiple threads, the program execution performance will decrease. Otherwise, if getInstance () is not frequently called by multiple threads, this delayed initialization solution will provide satisfactory performance.

In early JVMs, synchronized (or even non-competing synchronized) had this huge performance overhead. So people come up with a "smart" trick: double-checked locking ). People want to use double check locks to reduce synchronization overhead. The following is an example of code that uses the double check lock to implement delayed initialization:

Public class DoubleCheckedLocking {// 1 private static Instance instance; // 2 public static Instance getInstance () {// 3 if (instance = null) {// 4: the first check for synchronized (DoubleCheckedLocking. class) {// 5: lock if (instance = null) // 6: The second check instance = new Instance (); // 7: the root cause of the problem is} // 8} // 9 return instance; // 10} // 11} // 12

As shown in the code above, if the instance is not null for the first check, the following locking and initialization operations are not required. Therefore, synchronized performance overhead can be greatly reduced. On the surface, the above Code seems to have the best of both worlds:

  • When multiple threads try to create an object at the same time, the lock is used to ensure that only one thread can create an object.
  • After the object is created, execute getInstance () to directly return the created object without obtaining the lock.

Double check locks seem perfect, but this is a wrong optimization! When the thread executes the Code in line 4th and reads that the instance is not null, the object referenced by the instance may not have been initialized yet.

Root Cause

The previous double check locks the 7th line (instance = new Singleton ();) of the sample code to create an object. This line of code can be divided into the following three lines of pseudo code:

Memory = allocate (); // 1: memory space of the allocated object ctorInstance (memory); // 2: initialization object instance = memory; // 3: set the instance to point to the allocated memory address

In the preceding three lines of pseudo code, the two and three may be reordered (in some JIT compilers, such re-sorting is actually happening, for more information, see "Out-of-order writes" in reference 1 ). The execution sequence after sorting between 2 and 3 is as follows:

Memory = allocate (); // 1: memory space of the allocated object instance = memory; // 3: Set the instance to point to the allocated memory address. Note that the object has not been initialized yet! CtorInstance (memory); // 2: initialization object

According to The Java Language Specification, Java SE 7 Edition (hereinafter referred to as The Java Language Specification), All threads must comply with intra-thread semantics when executing java programs. Intra-thread semantics ensures that reordering does not change the execution results of programs in a single thread. In other words, intra-thread semantics allows reordering of the execution results of a single thread without changing the results. Although the two and three lines of pseudo code above are reordered, this re-sorting does not violate intra-thread semantics. This re-sorting can improve the program execution performance without changing the execution results of a Single-threaded program.

For A better understanding of intra-thread semantics, see the following (assuming that A thread A accesses this object immediately after constructing the object ):

As shown in, as long as 2 is at the top of 4, intra-thread semantics will not be violated even if it is reordered between 2 and 3.

Next, let's look at the multi-thread concurrent execution. See the following:

Because intra-thread semantics must be observed in A single thread, the program execution result of thread A can be ensured not to be changed. However, when threads A and B are executed in sequence, the B thread will see an object that has not been initialized.

※Note: In this document, incorrect read operations are identified by Red Virtual arrows and correct read operations are identified by green virtual arrows.

Return to the topic of this Article. If the 7th line (instance = new Singleton ();) of the DoubleCheckedLocking sample code is reordered, another concurrent thread, B, may judge that the instance is not null in row 4th. Thread B will access the object referenced by instance, but this object may not be initialized by thread A yet! The specific execution sequence of this scenario is as follows:

Time

Thread

Thread B

T1

A1: allocate the object's memory space

 

T2

A3: Set instance to point to memory space

 

T3

 

B1: determines whether the instance is null.

T4

 

B2: Because instance is not null, thread B will access the object referenced by instance

T5

A2: initialization object

 

T6

A4: access the object referenced by the instance

 

Although A2 and A3 are reordered, the intra-thread semantics of the java memory model ensures that A2 will be executed before A4. Therefore, the intra-thread semantics of thread A has not changed. However, the re-sorting of A2 and A3 will cause thread B to judge at B1 That the instance is not empty. Thread B will then access the object referenced by the instance. In this case, thread B will access an object that has not been initialized.

After knowing the root cause of the problem, we can come up with two ways to implement thread-safe delayed initialization:

The two solutions described later correspond to the preceding two solutions.

Volatile-based dual-check lock Solution

For the previous scheme to implement delayed initialization Based on Double Check locking (the DoubleCheckedLocking sample code), we only need to make a small modification (declare the instance as volatile type ), thread-safe delay initialization can be implemented. See the following sample code:

Public class SafeDoubleCheckedLocking {private volatile static Instance instance Instance; public static instance getInstance () {if (Instance = null) {synchronized (SafeDoubleCheckedLocking. class) {if (instance = null) instance = new Instance (); // The instance is volatile. Now it's okay.} return instance ;}}

Note that this solution requires JDK 5 or later (because the new JSR-133 memory model specification is used from JDK 5, which enhances the semantics of volatile ).

After the object is declared as volatile, the reconnection between 2 and 3 in the three lines of pseudo code of "root cause of the problem" will be disabled in the multi-threaded environment. The above sample code will be executed in the following sequence:

In essence, this scheme ensures thread-safe delay initialization by prohibiting the reconnection between 2 and 3.

Class-based initialization Solution

The JVM executes Class initialization in the Class initialization phase (that is, after the Class is loaded and used by the thread. During the initialization of the execution class, JVM will obtain a lock. This lock can synchronize multiple threads to initialize the same class. Based On this feature, we can implement another thread-safe delay Initialization solution (called Initialization On Demand Holder idiom ):

Public class InstanceFactory {private static class InstanceHolder {public static Instance instance = new Instance ();} public static Instance getInstance () {return InstanceHolder. instance; // this will cause the InstanceHolder class to be initialized }}

Assume that two threads concurrently execute getInstance (). The following statements are executed:

The essence of this solution is: allow two and three duplicates in the three lines of pseudo code of the "root cause of the problem", but do not allow non-constructor threads (here thread B) "see" This reorder.

Initialize a class, including executing static initialization of this class and initializing static fields declared in this class. According to the java language specification, when any of the following conditions occurs for the first time, a class or interface type T will be initialized immediately:

  • T is a class, and a T-type instance is created;
  • T is a class, and a static method declared in T is called;
  • A static field declared in T is assigned a value;
  • A static field declared in T is used, and this field is not a constant field;
  • T is a top-level class (see section 7. 6 of java standards), and an asserted statement is nested inside T.

In the InstanceFactory sample code, the first execution of the getInstance () thread will cause the InstanceHolder class to be initialized (Compliance 4 ).

Because Java is multi-threaded, multiple threads may attempt to initialize the same class or interface at the same time (for example, multiple threads may call getInstance () at the same time () to initialize the InstanceHolder class ). Therefore, when initializing a class or interface in java, careful synchronization is required.

The Java language specification specifies that each class or interface C has a unique initialization lock LC corresponding to it. The ing from C to LC is implemented freely by the specific implementation of JVM. JVM acquires the initialization lock during class initialization, and each thread obtains the lock at least once to ensure that the class has been initialized (in fact, the Java language specification allows the specific implementation of JVM to be optimized here, as described later ).

For Class or interface initialization, java language specifications have developed a sophisticated and complex class initialization process. Java initializes the processing process of a class or interface as follows (the class initialization process is described here, And the content irrelevant to this article is omitted; at the same time, to better describe the synchronization processing mechanism in the class initialization process, the author manually divides the class initialization process into five stages ):

Phase 1: control Class or interface initialization by synchronizing the Class Object (that is, obtaining the Class object initialization lock. The thread that obtains the lock will wait until the current thread can obtain the initialization lock.

Assume that the Class object is not initialized yet (the initialization state is marked as state = noInitialization at this time), and there are two threads A and B trying to initialize the Class object at the same time. Below is the corresponding:

The following is a description:

Time

Thread

Thread B

T1

A1: attempts to obtain the initialization lock of the Class Object. Assume that thread A has obtained the initialization lock.

B1: Try to get the initialization lock of the Class Object. Because thread A gets the lock, thread B will always wait to get the initialization lock.

T2

A2: When thread A sees that the thread has not been initialized (because it reads state = noInitialization), the thread sets state = initializing.

 

T3

A3: thread A releases the initialization lock.

 

Stage 2: Initialize thread A execution class, and thread B waits for the condition corresponding to the initialization lock:

The following is a description:

Time

Thread

Thread B

T1

A1: static initialization of the execution class and static fields declared in the initialization class

B1: the initialization lock is obtained.

T2

 

B2: Read to state = initializing

T3

 

B3: Release the initialization lock

T4

 

B4: wait in the condition of the initialization lock

Stage 3: thread A sets state = initialized and then wakes up all threads waiting in condition:

The following is a description:

Time

Thread

T1

A1: Get the initialization lock

T2

A2: Set state = initialized

T3

A3: Wake up all threads waiting in condition

T4

A4: Release the initialization lock

T5

A5: the initialization process of thread A is completed.

Stage 4: initialization of the end class of thread B:

The following is a description:

Time

Thread B

T1

B1: Get the initialization lock

T2

B2: Read to state = initialized

T3

B3: Release the initialization lock

T4

B4: the class initialization process of thread B is completed.

Thread A initializes the A1 execution class in the second stage and releases the initialization lock in the A4 of the third stage. Thread B obtains the same initialization lock in B1 of the fourth stage, and access this class only after B4 in Stage 4.

According to the lock rules defined in the java memory model, the following happens-before relationship exists:

This happens-before relationship ensures that thread B can see the write operations (static initialization of the execution class and static fields declared in the initialization class) during initialization of thread.

Stage 5: initialization of thread C execution class:

The following is a description:

Time

Thread B

T1

C1: Get the initialization lock

T2

C2: Read to state = initialized

T3

C3: Release the initialization lock

T4

C4: the class initialization process of thread C is completed.

After the third stage, the class has been initialized. Therefore, the class initialization process of thread C in the fifth stage is relatively simple (the class initialization process of thread A and thread B both experienced two lock acquisition-lock release, the class initialization process of thread C only requires one lock acquisition-lock release ).

Thread A initializes the A1 execution class in the second stage and releases the lock in the A4 of the third stage. Thread C acquires the same lock in C1 of the fifth stage, the class is accessed only after C4 in Stage 5.

According to the lock rules defined in the java memory model, the following happens-before relationship exists:

This happens-before relationship ensures that the write operation during initialization of thread A is visible to thread C.

※Note 1: the condition and state Mark here are fabricated in this document. The Java language specification does not require the use of the condition and state flag. For the specific implementation of JVM, you only need to implement similar functions.

※Note 2: the Java language specification allows the specific implementation of Java and the initialization process of the optimization class (the fifth stage is optimized here). For details, see chapter 12.4.2 of the java language specification.

By comparing the volatile-based dual-check lock solution and class-based initialization solution, we will find that the implementation code of the class-based initialization solution is more concise. However, the volatile-based dual-check lock solution has an additional advantage: in addition to the delay initialization for static fields, you can also implement delayed initialization for instance fields.

Summary

Delayed initialization reduces the overhead of initialization class or instance creation, but increases the overhead of access to delayed initialization fields. In most cases, normal Initialization is better than delayed initialization. If you do need to use thread-safe delay initialization for instance fields, use the volatile-based delay initialization solution described above. If you do need to use thread-safe delay initialization for static fields, use the class-based initialization solution described above.

References

Double check locking and delayed Initialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.