Java multi-thread design model Reading Notes 2
Directory:
1. Java Memory Model
2 single threaded execution pattern
3 guarded suspension Pattern
4 balking Pattern
5 producer-consumer pattern
6 read-write lock Pattern
= Java Memory Model =
the Java memory model is divided into two types: Primary memory and working memory.
the primary storage (which is independent of the primary storage on the hardware and is only an abstract concept) is the region where the instance is located. All instances exist in the primary storage. In particular, the fields owned by the instance are located in the primary storage area. The primary memory is shared by all threads. The work memory is the job zone owned by each thread, and all threads have their own dedicated work memory. There is a necessary copy in the primary memory, which is called a work copy.
the thread cannot directly operate on the primary storage, and therefore cannot directly reference the field value. When the thread needs to reference the field value, you need to copy it from the primary memory to your work memory. When you want to modify the field value, you must first modify the work copy, and then copy the modification from the work memory back to the master memory. When to complete the data image between the work memory and the master memory, Java executes the Processing System Decision.
fields shared by multiple threads are generally protected by synchronized or volatile.
synchronized is used to achieve thread sharing and mutual exclusion. Volatile is not responsible for thread sharing and mutex, but for memory synchronization.
synchronized: on the one hand, it creates a critical section, so that only one thread can be allowed to operate in this area at the same time. On the other hand, when entering and exiting the critical section, it executes the memory synchronization operation, the modification image of the current workspace to the primary storage. When synchronized is entered, in addition to the image of the working copy to the primary storage, it also releases the working copy of the working memory. If the value on the primary storage is referenced later, it must be copied from the primary storage to the working storage.
although the synchronization of memory occurs when synchronized is in and out, it is not clear when the synchronization of memory is "within synchronized" or "outside synchronized, depends on the Java running processing system.
in a single thread, memory synchronization is not considered. Of course, thread synchronization is not required.
volatile memory synchronization: When a thread wants to reference the value of the volatile field, the copy operation from the primary memory to the work memory usually occurs. Otherwise, after the value is specified to the volatile field, the work memory content is usually mapped to the primary storage. In addition, for the long and double types, the default value assignment operation is not Atomic. to specify these types of values in atomic mode, you need to use the volatile keyword. In this case, volatile implements atomic operations, instead of memory synchronization. Q: What if I want to specify memory synchronization for long and double fields? Can it be implemented only with synchronized?
============== Single threaded execution pattern ==================
When we modify the variables shared by multiple threads, the security of the variables will be lost. Therefore, we should carefully find out the range of variable status instability, set this range to a critical section, and apply protection to the critical section. At the same time, only one thread can execute this restriction. In Java, you can use the synchronized keyword to define the critical section to protect shared fields.
Applicability: data can be accessed by multiple threads and the status may change.
========================== Immutable pattern ==========================
After an instance of a class is declared, the state will not change at all. At this time, even if multiple threads call the method of this class at the same time, it does not matter, so the method is not necessary for synchronized. In this way, it can be improved without losing security and life.ProgramPerformance. To implement immutable of a class, you must be careful when implementing the class. do not provide methods or flaws that can change the instance status.
Java final usage
Final class: The final class cannot be inherited.
Final method: if it is an instance method, it cannot be overwritten by the quilt class. If it is a class method, it cannot be hidden by the quilt class.
Final field: the final field value can only be specified once, either initialized during declaration or assigned a value in the constructor (the static field is initialized in the static block ).
Final variables and parameters: the final variables can only be specified once when being defined, and the final parameter is set only when being called.
========================== Guarded suspension pattern ========================
When a condition is met, an action is executed directly. If the condition is not met, wait until the condition is met.
For example, in the Request queue, if the queue is already empty, the request must be waited for to be obtained. When a new request is added, the waiting thread is awakened.
Public synchronized request getrequest (){
While (queue. Size () <= 0 ){
Try {
Wait ();
} Catch (interruptedexception e ){}
Return (request) queue. removefirst ();
}
Public synchronized void putrequest (request req ){
Queue. addlast (req );
Policyall ();
}
============================= Balking pattern ======================
If you do not want to perform an operation, or you do not need to perform an operation, you can simply discard the operation and return it.
Public synchronized void save (){
If (! Changed ){
Return;
}
Dosave ();
Changed = false;
}
Use Cases: (1) when you do not need to deliberately execute (improve execution performance); (2) do not want to wait for alert conditions (improve responsiveness); (3) the alert condition is only valid for the first time (for example, initialization ).
============================= Producer-consumer pattern ======================
The producer-consumer mode assumes that the produced product is placed in a buffer with a limited length. If the buffer is full, the producer must stop placing the product in the buffer, until the consumer removes the product and has space, and if there is no product in the buffer zone, the consumer must wait until a new product is put in the buffer zone. Similar to the guarded suspension mode, but the guarded suspension mode does not limit the length of the buffer.
There may be multiple producers and multiple consumers. When there is only one producer and one consumer, it is also called pipeline pipe pattern.
Java mainly uses synchronized, wait and notify/notifyall methods to coordinate producer and consumer.
========================== Read-write lock pattern ========================
Read-write lock pattern separate read and write operations. Before reading data, you must obtain the lock for reading. When writing data, you must obtain the lock used for writing.
Because the instance status does not change during reading, it does not matter if multiple threads read data at the same time. However, some users cannot write data when reading data.
When writing data, the instance status changes. When a thread is writing data, other threads cannot read or write data. In general, the performance of the program may be deteriorated when shared mutex is implemented. However, the performance of the program can be improved by separating the shared mutex and read shared mutex.
In Java, using finally can avoid forgetting to unlock the lock. For example:
Get lock
Try {
Actual Operation
} Finally {
Unlock
}