In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you the Java memory model sequence consistency example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Brief introduction:
The sequential consistent memory model is a theoretical reference model. Both the processor memory model and the programming language memory model take the sequential consistent memory model as a reference.
1. Data competition and sequential consistency
When the program is not synchronized correctly, there may be data competition.
1.1 definition of data contention in the Java memory model specification
The definition is as follows:
Write a variable in a thread
Read the same variable in another thread
Write and read are not sorted by synchronization
If a multithreaded program can be synchronized correctly, the program will be a program without data competition, and there is often a data competition program, and the running results will deviate from our expected results.
1.2 JMM guarantees the memory consistency of multithreaded programs
If the program is synchronized correctly (using synchronized, volatile, and final correctly), the execution of the program will be sequentially consistent (Sequentially Consistent)-- that is, the execution result of the program is the same as that of the program in the sequential consistent memory model.
2. Sequence consistency memory model 2.1 features
All operations in a thread must be performed in the order in which the program is executed.
(whether synchronized correctly or not) all threads can only see a single order in which operations are executed, and each operation must be performed atomically and immediately visible to all threads.
Illustration: sequential consistency memory model view
Conceptually, the sequential consistency model has a single global memory, which can be connected to any thread through a switch that swings left and right, and each thread must read / write memory in the order of the program. As you can see in the figure above, at most one thread can connect to memory at any one time. Therefore, when multithreading is executed concurrently, the switchgear in the figure can serialize all memory read / write operations (that is, there is a full order relationship between all operations in the sequential consistency model).
2.2 give examples to illustrate the sequential consistency model
Suppose two threads An and B execute concurrently. Among them
The operation order of A thread in the program is A1-A2-A3.
The operation order of B thread in the program is B1-B2-B3.
Assuming that threads An and B use monitor locks to synchronize correctly, thread A releases the monitor lock after three operations are performed, and thread B then acquires the same monitor lock. Then the execution effect of the program in the sequential consistency model is as follows: an execution effect of the sequential consistency model.
Assuming that thread An and thread B are not synchronized, another possible effect of this unsynchronized program in the sequential consistency model is as follows:
Another execution effect of the sequential consistency model:
Although the overall execution order of unsynchronized programs is out of order in the sequential consistency model, all threads can only see an overall execution order all the time. As an example in the above figure, threads An and B see the execution order as follows: A1-B1-A2-B2-A3-B3. This guarantee can be achieved because each operation in the sequentially consistent memory model must be immediately visible to any thread.
However, there is no such guarantee in JMM. Not only is the overall execution order of unsynchronized programs out of order in JMM, but also the order of operations seen by all threads may be inconsistent. For example, when the current thread caches written data in local memory, the write operation is only visible to the current thread until it is flushed to the main memory; from the point of view of other threads, the write operation is considered to be performed by the current thread at all. This write operation is visible to other threads only after the current thread flushes the data written in the local memory to the main memory. In this case, there will be a variety of running results.
2.3 Sequential consistency effect of synchronous programs
Use locks to synchronize the ReorderExample program in the previous chapter
Package com.lizba.p1;/** *
* synchronization example *
* * @ Author: Liziba * @ Date: 21:44 on 2021-6-8 * / public class SynReorderExample {/ / defines the variable an int a = 0; / / the flag variable is a flag indicating whether the variable an is written to boolean flag = false; public synchronized void writer () {/ / acquire lock a = 1; flag = true } / / release lock public synchronized void reader () {/ / acquire lock if (flag) {int I = a * a; System.out.println ("I:" + I);}} / / release lock}
Test code
/ * Test * * @ param args * / public static void main (String [] args) {final SynReorderExample re = new SynReorderExample (); new Thread () {public void run () {re.writer ();}} .start (); new Thread () {public void run () {re.reader ();}} .start ();}
Execute multiple times and the result is 1.
Summary:
In the sample code above, assume that after thread An executes the writer () method, thread B executes the reader () method. This is a correctly synchronized multithreaded program. According to the JMM specification, the execution result of the program will be the same as that of the program in the sequential consistent memory model.
Execution sequence diagrams in Sequential consistency Model and JMM memory Model
Summary
In the sequential consistency model, all operations are performed in exactly the order of the program. In JMM, the code in the critical zone can be reordered (but JMM does not allow the code in the critical area to "escape" outside the critical area, which would break the semantics of the monitor lock). JMM will do some special processing at the critical time when entering and exiting the critical section, so that the thread has the same memory view in the sequential consistency model at these two time points. Although thread A reorders in the critical area, thread B cannot "observe" thread A's reordering in the critical zone because of the feature of monitoring lock mutex execution. The basic policy of JMM in concrete implementation is to open the convenient door for compiler and processor optimization as much as possible without changing (correctly synchronizing) the program execution results.
2.4 execution characteristics of unsynchronized programs
For brothers who do not synchronize or do not synchronize correctly (brothers whose code is wrong), JMM provides minimal security:
The value read by the thread during execution will not be created out of nothing (Out Of Thin Air)
A value previously written by a thread
Default value (0, Null, False)-JVM allocates objects when the memory space (Pre-zeroed Memory) has been cleared.
Comparison of execution characteristics of unsynchronized programs in two models
Compare content\ Model name Sequential consistency Model JMM Model Sequential execution within a single Thread √ × consistent Operation execution order √ × 64-bit long and long type variables write atomicity √ ×
The third difference relates to the mechanism of the bus. On some 32-bit processors, processing 64-bit data writes requires splitting a write operation into two 32-bit write operations.
3. 64-bit long and long type variables write atomicity 3.1 CPU, memory and bus brief
In a computer, data is transferred between processor and memory through bus, and each data transfer between processor and memory is accomplished through a series of steps, which are called bus transactions (Bus Transaction). Bus transactions include read transactions (Read Transaction) and write transactions (WriteTransaction), which read / write one or more physically contiguous words in memory.
Read transaction → memory to processor
Write transaction → processor to memory
Important: the bus synchronizes transactions that try to use the bus concurrently. While one processor is performing a bus transaction, the bus prohibits other processors and I / O devices from performing memory reads and writes.
Figure: bus working mechanism
As shown in the figure above: if processors A, B, C, and D simultaneously initiate bus transactions to the bus, the bus president (Bus Arbitration) will rule on the competition, which assumes that processor A wins the competition (bus arbitration ensures that all processors have fair access to memory). At this point, processor A continues its bus transaction, while all other bus transactions must wait for A's transaction to complete before performing memory read / write operations again. The bus transaction working mechanism ensures that the processor's access to memory is performed in a serial manner. Only one processor can access memory at any point in time, which ensures that memory read / write operations between bus transactions are atomic.
3.2 long and double type operations
On some 32-bit processors, there is a very high synchronization overhead if writing to 64-bit data is required to be atomic. The Java language specification encourages but does not require JVM to be atomic for variable writes of 64-bit long and double types. When JVM runs on such a processor, it splits a 64-bit variable write operation into two 32-bit write operations, which is not atomic.
Figure: timing diagram of bus transaction execution
There is a problem:
Suppose processor A writes a variable of type long, while processor B reads a variable of type long. 64-bit writes in processor An are split into two 32-bit writes, and the two 32-bit writes are assigned to different transactions for execution. At this point, 64-bit read operations in processor B are assigned to a single read transaction. If you follow the above execution order, processor B will read an incomplete invalid value.
Handling method:
At the beginning of the JSR-133 memory model (JDK1.5), writes can be split into two 32-bit write transactions, and reads must be performed in a single transaction.
The above is all the content of the article "sample Analysis of order consistency of Java memory Model". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.