Solving the problem of Java instruction reordering
The following editor will bring you a brief discussion on the issue of java instruction reordering. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let's follow the editor and take a look.
Command reordering is a relatively complicated and somewhat incredible problem. I also start with an example (it is recommended that you run the example, which can actually be reproduced. The probability of reordering is still quite high), I have a perceptual understanding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
The example is relatively simple, and comments have been added, so I will not describe it in detail.
What is instruction reordering? There are two levels:
At the virtual machine level, in order to minimize the impact of CPU vacancy caused by the memory operation speed being much slower than the CPU running speed, the virtual machine will follow some of its own The rule (this rule will be described later) disrupts the order in which the program is written - that is, the code written later may be executed first in chronological order, while the code written earlier will be executed later - in order to make full use of the CPU as much as possible. Take the above example: If it is not the operation of a=1, but a=new byte[1024*1024] (allocate 1M space)`, then it will run very slowly. At this time, the CPU is waiting for its execution to end. , or should we execute the following flag=true first? Obviously, executing flag=true first can use the CPU in advance and speed up the overall efficiency. Of course, this premise is that no errors will occur (what kind of errors will be discussed later). Although there are two situations here: the later code starts executing before the previous code; the previous code starts executing first, but when the efficiency is slow, the later code starts executing and ends before the previous code execution. No matter who starts first, there is a possibility that the following code will end first in some cases.
At the hardware level, the CPU will reorder the received batch of instructions according to its rules. This is also based on the reason that the CPU speed is faster than the cache speed. The purpose is similar to the previous point, except that for hardware processing, each Times can only be reordered within the limited range of instructions received, while the virtual machine can be reordered at a larger level and within a wider range of instructions. For the hardware reordering mechanism, please refer to "CPU Memory Reordering from JVM Concurrency"
Reordering is difficult to understand. The above just briefly mentions its scenarios. If you want to have a better understanding This concept requires the construction of some examples and charts. Here are two more detailed and vivid articles "happens-before explanation" and "In-depth understanding of Java memory model (2) - Reordering". Among them, "as-if-serial" should be mastered, that is: no matter how reordered, the execution result of the single-threaded program cannot be changed. The compiler, runtime, and processor all must adhere to "as-if-serial" semantics. Take a simple example,
1 2 3 4 5 |
|
The sentences a=0 and b=1 here can be sorted arbitrarily without affecting the logical result of the program, but c=a+b sentence must be executed after the first two sentences.
As you can see from the previous example, the probability of reordering in a multi-threaded environment is quite high. The keywords volatile and synchronized can disable reordering. In addition, there are some rules. , and it is these rules that prevent us from feeling the disadvantages of reordering in our daily programming work.
Program Order Rule: Within a thread, according to the code order, operations written in the front occur before operations written in the back. To be precise, it should be the control flow sequence rather than the code sequence, because structures such as branches and loops must be considered.
Monitor Lock Rule: An unlock operation occurs before a subsequent lock operation on the same object lock. The emphasis here is on the same lock, and "later" refers to the temporal sequence, such as lock operations that occur in other threads.
Volatile Variable Rule (Volatile Variable Rule): The writing operation of a volatile variable occurs after the reading operation of the variable. The "back" here also refers to the sequence in time.
Thread Start Rule: Thread’s exclusive start() method precedes every action of this thread.
Thread Termination Rule: Every operation in a thread occurs first in the termination detection of this thread. We can end it through the Thread.join() method and the return of Thread.isAlive() The value detects that the thread has terminated execution.
Thread Interruption Rule: The call to the thread interrupte() method takes precedence over the code of the interrupted thread to detect the occurrence of the interrupt event. You can use the Thread.interrupted() method to detect whether the thread has been interrupted. .
Object finalization principle (Finalizer Rule): The initialization of an object (the end of constructor execution) occurs first at the beginning of its finalize() method.
Transitivity: If operation A occurs before operation B, and operation B occurs before operation C, then we can conclude that operation A occurs before operation C.
It is the above rules that guarantee the order of happen-before. If the above rules are not met, then in a multi-threaded environment, there is no guarantee that the execution order is equal to the code order, that is, "if observed in this thread, all Operations are all in order; if you observe another thread in one thread, anything that does not meet the above rules is out of order." Therefore, if our multi-threaded program relies on the order of code writing, then we must consider whether it conforms to If the above rules are not met, some mechanisms must be used to make them comply. The most commonly used ones are synchronized, Lock and volatile modifiers.
The above is the detailed content of Solving the problem of Java instruction reordering. 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.
