Table of Contents
1.volatile" >1.volatile
2. The process of thread accessing data in the heap " > 2. The process of thread accessing data in the heap
3. Instruction rearrangement " > 3. Instruction rearrangement
Two common problems and solutions" > Two common problems and solutions
1. Atomicity problem" > 1. Atomicity problem
The occurrence of visibility problem is related to the way threads access shared data. When a thread accesses a variable in the heap (method area), it first creates a " > The occurrence of visibility problem is related to the way threads access shared data. When a thread accesses a variable in the heap (method area), it first creates a
In order to improve execution efficiency, the CPU will reorder instructions that have no dependencies. After reordering The execution result is the same as the sequential execution result. " > In order to improve execution efficiency, the CPU will reorder instructions that have no dependencies. After reordering The execution result is the same as the sequential execution result.
Home Java javaTutorial Sharing some issues about multi-thread concurrency

Sharing some issues about multi-thread concurrency

Jun 28, 2017 am 09:13 AM
common problem concurrent thread

Overview

1.volatile

Ensures that once the shared data is modified, it will be immediately synchronized to the shared memory (heap or method area).

2. The process of thread accessing data in the heap

The thread creates a copy of the variable in the stack, and after the modification is completed, the data is synchronized to in the pile.

3. Instruction rearrangement

In order to improve execution efficiency, the CPU will reorder instructions that have no dependencies. If you want to control reordering, you can use volatile to modify a variable. The instructions before and after the instruction containing the variable are ordered independently, and the instructions before and after cannot be cross-ordered.

Two common problems and solutions

1. Atomicity problem

The so-called atomicity, It means that an operation cannot be interrupted, that is, in a multi-threaded concurrent environment, once an operation is started, it will be executed within the same CPU time slice. If multiple operations of the same thread are executed on different CPU time slices, due to stagnation in the middle, some shared data may be modified by other threads during subsequent operations, and the modification is not synchronized. to the current thread, causing the data operated by the current thread to be inconsistent with the actual data. This data inconsistency problem caused by incoherent execution is called an atomicity problem. 2. Visibility problem

copy of the variable on the stack, and then synchronizes it to the heap after modification. If a thread has just created a copy, and another thread modifies the variable, which has not yet been synchronized to the heap,

At this time, there will be a phenomenon where two threads operate the same variable in the same state, such as i=9 , the initial value of variable i is 9, and the operation of each thread is to decrease 1. Two threads A and B access variables at the same time. B executes i-1 first. Before synchronizing the result i=8 to the heap, thread A also executes i-1. At this time, the state of i=9 is executed Twice, thread safety issues occurred. Reasons for thread safety issues: Modifications of shared data by one thread cannot be immediately seen by other threads.
volatile provides a solution:

Once a thread modifies the shared data modified by volatile, the modification will be immediately synchronized to the heap In this way, when other data accesses shared data from the heap, they always get the latest value in multiple threads.
Defects of volatile:
volatile can only guarantee that when a thread obtains data from the heap, it obtains the latest value among all current threads. If a Thread

has copied the data from the heap. Before the operation is completed, other threads modify the data. The modified data will not be synchronized to the current thread.

3. Ordering problem

In order to improve execution efficiency, the CPU will reorder instructions that have no dependencies. After reordering The execution result is the same as the sequential execution result.

For example, in the source code:
int i=0;
int y=1;
During execution, the CPU may first execute "int y=1;" and then "int i=0;". The execution result is the same as the sequential execution result.
Instruction reordering is safe in a single-threaded environment, but problems may occur in a multi-threaded environment. For example:
Thread A:

s=new String("sssss");//指令1flag=false;//指令2
Copy after login
Thread B:

while(flag){
doSome();
}
s.toUpperCase();//指令3
Copy after login

If thread A executes sequentially, that is, executes instruction 1 and then executes instruction 2, there will be no problem with the execution of thread B. After the instructions are rearranged, if thread A executes instruction 2 first,
This is flag=true, switches to thread 2, terminates the loop, and executes instruction 3. Since the s object has not yet been created, a null pointer will appear. abnormal.
Reasons for the ordering problem:

One thread has sequence requirements for other threads' modification operations on shared data. For example, thread B requires thread A First execute instruction 1, and then execute instruction 2. Due to the rearrangement of instructions, the instructions are not actually executed in the required order. At this time, thread safety issues arise.

Solution:

  1. Use the synchronization mechanism so that only one thread can access shared data at the same time, which is inefficient .

  2. Using volatile, an instruction contains volatile-modified variables, then the execution order of this instruction remains unchanged, and the instructions before and after the instruction can be independent Rearrange, cross-rearrangement is not possible.

refer to:

The above is the detailed content of Sharing some issues about multi-thread concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Application of concurrency and coroutines in Golang API design Application of concurrency and coroutines in Golang API design May 07, 2024 pm 06:51 PM

Concurrency and coroutines are used in GoAPI design for: High-performance processing: Processing multiple requests simultaneously to improve performance. Asynchronous processing: Use coroutines to process tasks (such as sending emails) asynchronously, releasing the main thread. Stream processing: Use coroutines to efficiently process data streams (such as database reads).

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

How does Java database connection handle transactions and concurrency? How does Java database connection handle transactions and concurrency? Apr 16, 2024 am 11:42 AM

Transactions ensure database data integrity, including atomicity, consistency, isolation, and durability. JDBC uses the Connection interface to provide transaction control (setAutoCommit, commit, rollback). Concurrency control mechanisms coordinate concurrent operations, using locks or optimistic/pessimistic concurrency control to achieve transaction isolation to prevent data inconsistencies.

C++ Concurrent Programming: How to avoid thread starvation and priority inversion? C++ Concurrent Programming: How to avoid thread starvation and priority inversion? May 06, 2024 pm 05:27 PM

To avoid thread starvation, you can use fair locks to ensure fair allocation of resources, or set thread priorities. To solve priority inversion, you can use priority inheritance, which temporarily increases the priority of the thread holding the resource; or use lock promotion, which increases the priority of the thread that needs the resource.

C++ Concurrent Programming: How to do thread termination and cancellation? C++ Concurrent Programming: How to do thread termination and cancellation? May 06, 2024 pm 02:12 PM

Thread termination and cancellation mechanisms in C++ include: Thread termination: std::thread::join() blocks the current thread until the target thread completes execution; std::thread::detach() detaches the target thread from thread management. Thread cancellation: std::thread::request_termination() requests the target thread to terminate execution; std::thread::get_id() obtains the target thread ID and can be used with std::terminate() to immediately terminate the target thread. In actual combat, request_termination() allows the thread to decide the timing of termination, and join() ensures that on the main line

Golang process scheduling: Optimizing concurrent execution efficiency Golang process scheduling: Optimizing concurrent execution efficiency Apr 03, 2024 pm 03:03 PM

Go process scheduling uses a cooperative algorithm. Optimization methods include: using lightweight coroutines as much as possible to reasonably allocate coroutines to avoid blocking operations and use locks and synchronization primitives.

How to use atomic classes in Java function concurrency and multi-threading? How to use atomic classes in Java function concurrency and multi-threading? Apr 28, 2024 pm 04:12 PM

Atomic classes are thread-safe classes in Java that provide uninterruptible operations and are crucial for ensuring data integrity in concurrent environments. Java provides the following atomic classes: AtomicIntegerAtomicLongAtomicReferenceAtomicBoolean These classes provide methods for getting, setting, and comparing values ​​to ensure that the operation is atomic and will not be interrupted by threads. Atomic classes are useful when working with shared data and preventing data corruption, such as maintaining concurrent access to a shared counter.

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

See all articles