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

A brief introduction to the Java memory Model happens-before

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "A brief introduction to the Java memory model happens-before". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Happens-before principle is very important, it is the main basis to judge whether there is competition in data and thread safety. Based on this principle, we solve all the problems that there may be conflicts between two operations in a concurrent environment. Let's take a simple example to learn a little about happens-before.

I = 1; / / Thread An execution

J = I; / / Thread B execution

Is j equal to 1? Assuming that the operation of thread A (I = 1) happens-before the operation of thread B (j = I), then it can be determined that j = 1 must be true after thread B executes, and if they do not have the happens-before principle, then j = 1 may not be true. This is the power of the happens-before principle.

The happens-before principle is defined as follows:

1. If one operation happens-before another operation, the execution result of the first operation will be visible to the second operation, and the execution order of the first operation comes before the second operation.

two。 The existence of a happens-before relationship between the two operations does not mean that they must be performed in the order established by the happens-before principles. If the execution result after the reorder is consistent with the result performed according to the happens-before relationship, then the reorder is not illegal.

Here are the happens-before principles and rules:

1. Program order rule: within a thread, according to the code order, the operation written in front occurs first in the operation written later.

two。 Locking rule: a unLock operation occurs first on the same lock forehead lock operation.

3.volatile variable rule: the write operation to a variable occurs first in the subsequent read operation on the variable

4. Transfer rule: if operation An occurs first in operation B, and operation B occurs in operation C first, it can be concluded that operation An occurs in operation C first.

5. Thread startup rule: the start () method of the Thread object occurs first in each action of this thread

6. Thread interrupt rule: the call to the thread interrupt () method occurs first in the code of the interrupted thread to detect the occurrence of the interrupt event

7. Thread termination rule: all operations in a thread first occur in the termination detection of the thread. We can detect that the thread has terminated execution through the termination of the Thread.join () method and the return value of Thread.isAlive ().

8. Object termination rule: the initialization of an object occurs first at the beginning of its finalize () method

Let's take a closer look at each of the above rules (excerpted from "in-depth understanding of the Java Virtual Machine Chapter 12"):

Program order rules: the results of a piece of code executed in a single thread are ordered. Note that it is the result of execution, because the virtual machine and processor will reorder the instructions (which will be described in more detail later). Although it is reordered, it does not affect the execution result of the program, so the final execution result of the program is consistent with that of sequential execution. Therefore, this rule is only valid for single thread and cannot guarantee correctness in multithreaded environment.

Volatile variable rule: this is an important rule that marks that volatile ensures thread visibility. Generally speaking, if a thread first writes a volatile variable, and then a thread reads the variable, then the write operation must be a happens-before read operation.

Transfer rule: withdraw the happens-before principle with transitivity, that is, A happens-before B, B happens-before C, then A happens-before C

Thread startup rule: assuming that thread A starts thread B by executing ThreadB.start () during execution, thread A's modification of the shared variable ensures that it is visible to thread B after thread B starts execution.

Thread termination rule: assuming that thread A waits for thread B to terminate by making ThreadB.join () during execution, thread B's modification of the shared variable before termination is visible after waiting for return.

The above eight are the rules that native Java satisfies the Happens-before relationship, but we can deduce other rules that satisfy happens-before from them:

1. The operation of putting an element in a thread-safe queue Happens-Before the operation of fetching the element from the queue

two。 The operation of putting an element in a thread-safe container Happens-Before the operation of fetching the element from the container

3. Countdown operation on CountDownLatch Happens-Before CountDownLatch#await () operation

4. Release the Semaphore licensed operation Happens-Before obtains the licensed operation

All operations Happens-Before Future#get () operations of the task represented by 5.Future

6. Submit an operation of Runnable or Callable to Executor the Happens-Before task begins to execute the operation

Let's repeat the concept of happens-before: if either of the above (the first 8 + the last 6) happens-before rules does not exist for the two operations, then there is no guarantee of order for the two operations, and JVM can reorder the two operations. If operation A happens-before operation B, then what operation A does in memory is visible to operation B.

Here is a simple example to describe the happens-before principle:

Private int i = 0 return public void write (int j) {I = j;} public int read () {public I;}

We agree that thread An executes write (), thread B executes read (), and thread A takes precedence over thread B, so what is the result of thread B? Let's analyze the rules of happens-before for this simple code at once (the 6 rules derived from rules 5, 6, 7, 8 + can be ignored because they have nothing to do with this code):

1. Since the two methods are called by different threads, they certainly do not satisfy the program order rules.

two。 Neither method uses a lock, so it does not satisfy the locking rule

3. The variable I is not modified with volatile, so the volatile variable rules are not satisfied

4. The delivery rules are definitely not satisfied.

So we can not derive thread A happens-before thread B from the happens-before principle, although we can confirm that thread A takes precedence over thread B in time, but we just can't confirm what the result of thread B is, so this code is not thread safe. So how do you fix this code? Either Rule 2 or Rule 3 can be satisfied.

Happen-before principle is a very important principle in JMM. It is the main basis to judge whether there is competition in data and thread safety, and ensures the visibility in multi-thread environment.

The following is a diagram of the relationship between happens-before and JMM

This is the end of "A brief introduction to the Java memory model happens-before". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report