Java multithreading concepts
Preface
This article introduces some in-depth concepts related to multithreading. After understanding, we will have a deeper understanding of thread security.
Let's start with a motto from the core Java technology:
If a value is written to a variable, the variable may be read by another thread; or a variable read value. The variable may have been written by another thread and must be synchronized at this time.
Here is the concept.
1. Monitor mechanism:
-
Monitor is actually a synchronization tool and mechanism. It is usually described as an object and has the following features:
-
In the Monitor Object mode, there are four main types of participants:
-
In Java, the Object class itself is the Monitored Object. Java provides built-in support for the Monitor Object mode.
- The Object class itself is the Monitored Object
- Each Object carries an invisible Lock, usually called internal Lock/Monitor Lock/Instrinsic Lock, which is a monitoring Lock.
- The synchronized keyword modifier and the code block are the synchronization methods.
- The wait ()/notify ()/policyall () method constitutes the monitoring Condition)
2. Memory Model
Java adopts the shared memory model for concurrency. Inter-thread communication is implicit and synchronization is displayed. In Android, Handler Communication is a message passing model, communication is displayed, and synchronization is implicit.
-
Classification of concurrent programming models
In concurrent programming, two problems need to be dealt with: how to communicate between threads and how to synchronize between threads.
- Communication refers to the mechanism by which threads exchange information. In imperative programming, there are two communication mechanisms between threads: Shared Memory and message transmission.
In the concurrency model of shared memory, threads implicitly communicate with each other through the public state in the write-Read Memory. In the message passing model, there is no public state between threads, communication must be carried out through explicit sending information.
- Synchronization refers to the mechanism by which a program is used to control the relative sequence of operations between different threads.
In the shared memory concurrency model, synchronization is performed. The programmer must specify a code or method that must be mutually exclusive among threads. In the message passing model, because the message must be sent before receiving the message, synchronization is performed implicitly.
-
Java Memory Model Abstraction
There is a thread sharing in the Java heap. The shared variables mentioned below are stored in the heap memory variables: instance domain, static domain, and array. Local variables, method-defined parameters, and exception handling parameters are not shared between threads, there is no memory visibility problem, and they are not affected by the memory model.
-
Communication between Java threads is controlled by the Java Memory Model (JMM, Java Memory Module). JMM determines when a thread writes shared variables to another thread.
JMM defines the abstract relationship between the thread and the main memory: Shared variables between threads are stored in the main memory. Each thread has a private local memory, also called the working memory, the local memory stores a copy of the shared variable that the thread reads/writes. (Local memory is an abstract concept of JMM and does not actually exist. It covers cache, write buffer, registers, and other hardware and compiler optimizations .)
The communication steps between thread A and thread B are as follows:
-
Thread model Diagram
3. atomicity
Atomicity indicates that an operation (which may contain multiple sub-Operations) is either executed (effective) or not executed (not effective ).
Many classes in the java. util. concurrent. atomic package use CAS commands to ensure atomicity, instead of using locks. For exampleAtomicInterger,AtomicBoolean,AtomicLong,AtomicReference.
Atomicity does not guarantee sequence consistency, but only ensures that the operation is atomic.
4. Memory visibility
Visibility means that when multiple threads concurrently access Shared variables, one thread modifies the shared variables and other threads can immediately see them.
- As you can see from the above thread model, thread a puts the value in its working memory before modifying the shared variable, and then updates the shared variable in the working memory to the main memory; this is also true for thread B. After thread a updates the main memory, thread B refresh the working memory and the latest value of thread a is displayed. This is the memory visibility problem.
- Two aspects of memory visibility must be ensured:
5. happens-before
Happens-before rules correspond to one or more compiler and processor reordering rules, which are easy to understand for programmers, avoid Learning complex re-sorting rules and the specific implementation of these rules to understand the memory visibility guarantee provided by JMM.
Use the concept of happens-beforeDescribes memory visibility between operations.
If the execution result of one operation needs to be visible to another operation, there must be a happens-before relationship between the two operations.
These two operations can be in one thread or different threads.
There is a happens-before relationship between the two operations, which does not mean that the previous operation must be executed before the next operation. Only the execution results of the previous operation must be visible to the next one, the previous operation is placed before the second operation in order.
- Transfer rule: if action 1 is before action 2 and Action 2 is before action 3, Action 1 is before action 3. This rule indicates that the happens-before principle is passed.
- Lock rule: an unlock operation will certainly occur before the lock operation of the same lock. It is easy to understand that the lock will be acquired again only when it is released.
- Volatile variable rules: Read operations for a volatile-modified write operation first created before the variable
- Program order rules: executed in the same thread in the code order
- Thread startup rules: the start () method of the Thread object is first generated in other actions of this Thread
- Thread termination principle: the thread termination detection is generated after all other operations in the thread.
- Thread interruption rule: the call to the interrupt () method of the thread is first generated when the exception of the interrupt is obtained.
- Object termination rules: an object is constructed prior to its finalize.
6. CAS commands
It is an efficient machine-level atomic Command provided by modern processors. These atomic commands perform read-write-modify operations on the memory in an atomic manner, which is the key to achieving synchronization in multiple processors.
AtomicInterger,AtomicBoolean,AtomicLongThe implementation is based on CAS commands.
7. reorder
In computer systems, software and hardware technologies share a common goal: to improve development concurrency as much as possible without changing program execution results.
- The compiler and processor reorder commands to improve performance. There are three types of re-sorting:
- These re-sorting may cause memory visibility problems in multi-threaded programs.
JMM requires the compiler to insert a specific typeMemory barrierCommand to disable the re-arrangement of a specific type of processor.
JMM is a language-level memory model that ensures memory visibility by disabling some reordering issues on different compilers and different processor platforms.
-
As-if-serial Semantics
It means that the execution results of a Single-threaded program cannot be changed no matter how the program is re-ordered. The compiler, runtime, and processor must comply with the as-if-serial syntax.
Therefore, the compiler and the processor do not re-Sort operations with data dependencies, because such re-sorting will change the execution result.
-
Data Dependency
- There are three types:
- For example:
Int a = 1; int B = 1; int sum = a + B;
There is no data dependency between A and B, but sum is dependent on A and B. Therefore, the execution sequence may be ABsum or BAsum.
-
Influence of reordering on Multithreading
Deduplication destroys the semantics of multi-threaded programs. For operations (if statements) with control dependencies, the execution result is not changed because the single-threaded program is executed in order. In multi-threaded programs, re-sorting may change the running result.
Control dependencyif(flag){b = a*a}The reordering of is as follows. The compiler and processor will use speculative execution to overcome the effect of relevance on the degree of parallelism. For first extracting and calculating a *, then, save the computing result to the hardware cache with the name as the sorting buffer, and then judge whether the flag is true. The other thread is set to true and a = 1. However, the obtained value may be 0, which is not as expected. This is a case of impact.
-
An example of reordering is taken from javastivejava:
While (! Done) {I ++} // After shuffling. This kind of optimization is called a prompt. It is the work of the spot Server VM if (! Done) {while (true) {I ++ ;}}8. Sequence consistency
If a multi-threaded program can be correctly synchronized, this program will be a program without data competition. JMM ensures the memory consistency of the correctly synchronized multi-threaded program as follows: if the program is correctly synchronized, the program execution will be sequential, that is, the execution result of the program is the same as that of the program in the sequential consistency memory model.
- Two features of the sequential consistency Memory Model (which provides strong memory visibility for programmers:
- Differences Between Sequence consistency and atomicity
Atomicity ensures the atomicity of operations, rather than sequence consistency.
9. volatile domain
First of all, it should be clear that thread security requires three guarantees: atomicity, visibility, and sequence. The thread is safe only when the three conditions are met.
- Once a shared variable (the member variable of the class and the static member variable of the class) is modified by volatile, it has two layers of semantics:
-
Synchronized and Lock fully guarantee these three points. volatile only guarantees visibility and order (prohibit command rescheduling). In some cases, you can use volatile instead of synchronized to improve performance. In this case, volatile is a lightweight synchronized.
-
In some cases:
If you do not assign values to shared variables, you can declare these shared variables as volatile.That is to say, the operation of the shared variable itself is atomic and ordered, and only visibility is missing. In this case, the volatile keyword can be used. Make careful analysis when using it.
Specifically:
- Write operations on variables do not depend on the current value.
- This variable is not included in the variant with other variables.
-
Remember, atomicity refers to the operation on shared variables (including its suboperations, that is, multiple statements), which is one piece, either executed or not executed. It doesn't mean that the use of AtomicInteger is atomic, but whether the operation on the shared variable AtomicInteger is multiple statements or whether these statements are atomic.
Boolean volatile isRunning = false; public void start () {new Thread ()-> {while (isRunning) {someOperation ();}}). start ();} public void stop () {isRunning = false; // only assign values, not multiple statements}
I have a public account that will often share some Java-related things. If you like it, you can search for "Java headers" or "javatuanzhang.
Refer:
- Java (2) What are we talking about when we talk about thread security?
- Java concurrent programming: volatile keyword Parsing
- Concurrency model-shared memory model (thread and lock) Theory