How to analyze double check locking in JAVA language
1. Double check locking
In program development, sometimes it is necessary to postpone some high-cost object initialization operations and only initialize them when these objects are used. In this case, you can Use double-checked locking to delay object initialization operations. Double-check locking is a software design pattern designed to reduce competition and synchronization overhead in concurrent systems. Based on the ordinary singleton pattern, it first determines whether the object has been initialized, and then decides whether to lock it. Although double-checked locking solves the error-prone and thread-unsafe problems of ordinary singleton patterns in multi-threaded environments, there are still some hidden dangers. The following takes the JAVA language source code as an example to analyze the causes and repair methods of double-check locking defects.
2. Double check lockingDangers
Double check locking has no impact in a single-threaded environment. In a multi-threaded environment, due to Threads will switch executions at any time. When instructions are rearranged, the object is not completely instantiated, resulting in program call errors.
3. Sample code
The example comes from Samate Juliet Test Suite for Java v1.3 (https://samate.nist.gov/SARD/testsuite.php ), source file name: CWE609_Double_Checked_Locking__Servlet_01.java.
3.1 Defect Code
The above code lines are 23 to 38. The program first determines whether stringBad
Is null, if not, the String
object will be returned directly, thus avoiding the resources required to enter the synchronized
block. Use the synchronized
keyword to avoid multiple creations of String
objects in a multi-threaded environment when stringBad
is null. When the code is actually run, errors may still occur in the above code.
For line 33, the creation of the stringBad
object and the assignment operation are performed in two steps. But the JVM does not guarantee the order of these two operations. When the instructions are reordered, the JVM will first assign the value pointing to the memory address, and then initialize the stringBad
object. If there are two threads at this time, both threads enter line 27 at the same time. Thread 1 first enters the synchronized
block, and since stringBad
is null, it executes line 33. When the JVM reorders the instructions, the JVM first allocates the empty memory of the instance and assigns it to stringBad
, but at this time the stringBad
object has not yet been instantiated, and then thread 1 left synchronized
blocks. When thread 2 enters the synchronized
block, since stringBad
is not null at this time, the uninstantiated object is directly returned (only the memory address value, the object is not actually initialized). When subsequent thread 2 calls the program to operate on the stringBad
object, the object at this time has not been initialized, so an error occurs.
Use 360 Code Guard to detect the above sample code, and you can detect the "double check lock" defect, and the display level is medium. The defect is reported at line 27 of the code, as shown in Figure 1:
Figure 1: Detection example of "Double Check Lock"
3.2 Fix code
In the above repair code, use the volatile
keyword in line 23 to modify the singleton variable stringBad
. volatile
As an instruction keyword, it ensures that the instruction will not be omitted due to compiler optimization and requires direct reading of the value each time.
Due to compiler optimization, the actual execution of the code may be different from the order we wrote. The compiler only guarantees that the program execution result is the same as the source code, but does not guarantee that the order of the actual instructions is the same as the source code. It will not go wrong in a single-threaded environment. However, once a multi-threaded environment is introduced, this kind of disorder may cause serious problems. . The volatile
keyword can solve this problem semantically. It is worth noting that the prohibition of instruction reordering optimization function of volatile
was only implemented in Java 1.5, so the version before 1.5 is still is unsafe, even if the volatile
keyword is used.
Use 360 Code Guard to detect the repaired code, and you can see that the "double check lock" defect no longer exists. As shown in Figure 2:
Figure 2: Detection result after repair
4, how to avoid double check lock
To avoid double-check locking, you need to pay attention to the following points:
(1) Use the volatile keyword to avoid instruction reordering, but this solution requires JDK5 or higher, because it is used starting from JDK5 The new JSR-133 memory model specification, which enhances the semantics of volatile.
(2) Solution based on class initialization.
The JVM will perform the initialization of the class during the initialization phase of the class (that is, after the Class is loaded and before it is used by the thread). During the initialization of the execution class, the JVM will acquire a lock. This lock can synchronize the initialization of the same class by multiple threads.
The above is the detailed content of How to analyze double check locking in JAVA language. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
