Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of memory model in Java?

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Java memory model in the principle of what, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need to learn, I hope you can gain something.

1. JMM brief knowledge

semantics

The semantics of the Java programming language allow compilers and microprocessors to perform optimizations to interact with incorrectly synchronized code to get the job done.

In-thread semantics are the semantics of single-threaded programs that allow the behavior of a thread to be fully predicted based on the values seen by the in-thread read operation; since the in-thread implementation is executing in its context, it is possible to determine whether an executing thread's operation is legal by evaluating the thread's implementation.

The program obeys intraleaded semantics: In thread isolation, each thread's operations must be governed by that thread's semantics, but the value seen by each read operation is determined by the memory model.

JMM Specification

From the data storage, for read and write operations of shared data,JMM will read and write data through thread working memory and heap memory of JVM (analogy Internet business, working memory analogy is redis cache, heap memory analogy is data storage carrier, such as database)

From code optimization,JMM in order to improve performance, will be for the program sequence code to reorder or even remove unnecessary synchronization code

JMM Summary

Given a program and an execution trace that detects whether the program is legitimate,JMM works by examining each read in the execution trace and checking whether the observed writes are valid according to certain rules

It is important to ensure that each result of execution is consistent with the expected values of the memory model, so it can be independent of how the implementer implements the behavior of the program

The memory model determines which values can be read at each point in the program. In isolation, the actions of each thread must be governed by the semantics of that thread, but the value seen by each read operation is determined by the memory model

Each time a write to a variable within a thread produces an inter-thread action, it must match the inter-thread action of the read action immediately following it in program order, where the read action for the thread gets the value determined by JMM.

2. JMM and Sequential Consistency Model

Program sequence and sequence consistency

program order

All actions that can be described as inter-thread are a collection of operations that are executed in order according to intra-thread semantics

In short, WYSIWYG is the sequence of operations within a thread, the sequence of program code.

Sequentially consistent memory model

All operations of a thread must be performed in the order of the program

All threads see only a single order of execution of operations, whether or not they are synchronized, and each operation must be atomic and immediately visible to all other threads

sequence consistency problem

If the memory model uses a consistent model, it will cause compiler and processor optimization strategies to become illegal.

JMM's efforts in order consistency

source code

// shared.java

int pwrite = 0;

int cwrite = 0;

// producer.java

int pread = 0;

int r1 = 0;

run(){

r1 = 20; // --- 1

pread = cwrite; // --- 2

pwrite = 10; // --- 3

}

// consumer.java

int cread = 0;

int r2 = 0;

run(){

cread = pwrite; // --- 4

r2 = 21; // --- 5

cwrite = 20; // --- 6

}

code analysis

Based on JMM model: due to data contention, the above code execution order will be in the compiler stage,JMM allows reordering of the program code, the output results will appear pread = cwrite = 20 and cread = pwrite = 10

Consistent memory model: output will be normal, there will be no pread = cwrite = 20 and cread = pwrite = 10, but the order between threads will alternate

locking scheme

Based on JMM model: output is guaranteed to be normal, but the order of execution within the above threads is reordered

Consistent memory model: no disorder, still normal output

summary

In the presence of data contention,JMM can not guarantee the execution order between threads, but order consistency guarantees the same order as code execution, even if the execution order of threads has alternate execution, it does not affect the execution order within a single thread.

In a single thread,JMM still reorders critical section execution actions, while order consistency does not reorder and remains in the same order as program code

3. JMM specification combing

shared data rule

Memory areas that can be shared by multiple threads are called shared memory or heap memory

Threads share data: all object instance fields,static fields, array elements, etc.

Thread-enclosed data: local variables, method parameters, exception handlers, and ThreadLocal/ThreadLocalRandom

thread operation rule

The equivalent thread behavior can be seen by other threads, and can also detect the behavior of other threads. The program behavior is as follows:

Normal read operations can be performed

Normal write operations can be performed

For synchronization code blocks

reads of volatile data can be performed, indicating that write operations of other threads can be "seen" by the current thread (write operations read main memory directly after thread failure)

Write volatile data can be performed, indicating that variable data can be "visible" to other threads

lock lock monitor

unlock unlock monitor

The first and last actions executed by the thread merge (personally understood as waiting for multiple threads to execute subtasks before executing the subsequent code of the program together)

Start threads and terminate threads

Synchronization principle (can be perceived, visible behavior change)

The unlocking of monitor m is synchronized with the locking operation of the subsequent action of monitor m

Threads write to volatile variable v in synchronization with all subsequent reads of v by any thread

Start the thread's operation synchronized with the thread's first action

The write operation that performs default values on each property in the thread is synchronized with the first action operation of the thread

The final action T1 in a thread is synchronized with any action in another thread T2 that detects that T1 has terminated

If thread T1 interrupts thread T2, then that interrupting thread T1 will synchronize with any point at which any other thread (including T2) determines that T2 has been interrupted (by raising an InterruptedException or calling Thread.interrupted or Thread.isInterrupted).

Happen-Before principle (specification)

Happen-before relationships between execution actions

If two actions x and y, we define hb(x,y) to describe x happens before y, satisfying the following relation:

If actions x and y are executed in the same thread, x takes precedence over y in program order, then hb(x,y)

The end of the object constructor code block happen-before the beginning of the object finalizer

If x moves synchronously with the next y move, then hb(x,y)

transitivity, if hb(x,y) and hb(y,z), then hb(x,z)

Happen-before principle

It mainly affects the execution order of conflicts between two actions and defines the timing of data competition. The specific VM implementation follows the following principles:

Thread unlock actions all happen-before subsequent actions of this thread lock operations

Write to volatile variable happen-before every action subsequent to read of this variable

Call the thread's start() method happen-before any action within an already opened thread

All actions of a thread happen-before any other thread successfully returns from the join() method of the thread object

Initialization of any object in the program happen-before any other action in the program

role

Following the above principles means that some code cannot be reordered and some data cannot be cached (specifications addressing JMM visibility)

Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report