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

How to realize the visibility and ordering of multithreading in Java

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is about how to achieve multi-threaded visibility and order in Java. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

Visibility of multithreading

Changes made by a thread to the value of a shared variable can be seen by other threads in time.

Shared variable

If a variable has a copy in the working memory of multiple threads, then this variable is the shared variable of the threads.

Java memory model

JMM (Java Memory Model, referred to as JMM) describes the access rules of various variables (thread-shared variables) in Java programs, as well as the low-level details such as storing variables in memory and reading variables from memory in JVM. It follows four principles:

All variables are stored in main memory

Each thread has its own independent working memory, which holds a copy of the variable used by the thread (a copy of the variable in the main memory).

All operations on shared variables by a thread must be performed in its own working memory and cannot be read or written directly from the main memory.

Variables in the working memory of other threads cannot be accessed directly between different threads, and the transfer of variables between threads needs to be completed through the main memory.

The principle of visibility implementation of shared variables

Thread 1's modifications to shared variables must go through the following two steps in order to be seen by thread 2 in time:

Refresh the updated shared variables in working memory 1 to main memory

Update the value of the latest shared variable in main memory to working memory 2

Java's memory model:

There are two visibility implementations supported at the Java language level:

Synchronized

Volatile

Synchronized

JMM's regulations on synchronized:

Before the thread is unlocked, the latest value of the shared variable must be refreshed to main memory

When a thread is locked, the value of the shared variable stored in the working memory is cleared, so when using the shared variable, the latest value must be reread from the main memory. (note: unlocking and locking refer to the same lock)

So the thread executes the synchronized code to execute the mutex:

Get the mutex.

Clear the working memory.

Copy the latest copy of the variable from main memory to working memory.

Execute the code

Refresh the value of the changed shared variable to main memory

Release mutex

Synchronize has made a lot of optimizations after JDK6. For more instructions on synchroinzed, click to view: explain the synchronized of Java multithreaded locks in detail.

Volatile

Atomicity is not guaranteed, but it is suitable to use volatile modified state marker quantity.

By adding a memory barrier and prohibiting reordering optimization

Insert StoreStore barrier before each volatile write operation and StoreLoad barrier after write operation

Insert the LoadLoad barrier before each volatile read operation and the LoadStore barrier after the read operation

Generally speaking: every time a volatile variable is accessed by a thread, it forces the value of the variable to be reread from the main memory, and when the variable changes, it forces the latest value to be refreshed to the main memory. In this way, different threads can always see the latest value of the variable at any time.

Volatile write operation:

Volatile read operation:

Ordering of multithreading

In the Java memory model, the compiler and processor are allowed to reorder instructions, but the reordering process does not affect the execution of single-threaded programs, but affects the correctness of multithreaded concurrent execution.

Instruction reordering: the order in which the code is written is different from the order in which it is actually executed. Instruction reordering is an optimization made by the compiler or processor to improve program performance.

Reordering of compiler optimization (compiler optimization)

Instruction set parallel reordering (processor optimization)

Reordering of memory systems (processor optimization)

Happens-before principle

JMM can provide programmers with cross-thread memory visibility through happens-before relationships (if there is an happens-before relationship between thread A's write operation an and thread B's read operation b, although an operation and b operation are performed in different threads, JMM assures the programmer that an operation will be visible to b operation).

Program order rules: the execution results of a piece of code within a thread are orderly. It will also rearrange the instructions, but no matter how it is arranged, the result will not change according to the order of our code!

Pipe locking rule: whether in a single-threaded or multithreaded environment, for the same lock, after one thread unlocks the lock, another thread acquires the lock and can see the result of the previous thread's operation! (pipe program is a general synchronization primitive, and synchronized is the implementation of pipe program)

Volatile variable rule: if a thread writes a volatile variable and then a thread reads it, the result of the write operation must be visible to the thread reading it.

Transitive rules: the happens-before principle is transitive, that is, A happens-before B, B happens-before C, then A happens-before C.

Thread startup rule: during the execution of main thread A, child thread B is started, then the result of thread A's modification of shared variables before starting child thread B is visible to thread B.

Thread termination rule: when child thread B terminates during the execution of main thread A, the modification of shared variable by thread B before termination is visible in thread A.

Thread interrupt rule: the call to the thread interrupt () method first occurs when the interrupted thread code detects the occurrence of the interrupt event, and the interrupt can be detected by Thread.interrupted ().

Object termination rule: the completion of the initialization of an object, that is, the end of the constructor execution must happens-before its finalize () method.

The above is how to achieve multi-threaded visibility and order in Java. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.

Share To

Internet Technology

Wechat

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

12
Report