In addition to adding a tell cache to the hardware, in order for the operating unit within the processor to be utilized as far as possible, the processor may perform a random execution (Out-of-order execution) optimization of the input code, and the processor will reorganize the results of the order execution after the calculation. Ensure that the result is consistent with the sequential execution, but there is no guarantee that the order of each statement in the program is consistent with the order in the input code, so if there is a calculation task that relies on the intermediate result of another computational task, the order is not guaranteed by the order of the Code. Similar to the processor's order-optimized execution, the Java Virtual machine's instant compiler also has similar command reordering (instruction Reorder) optimizations.
Java memory model
The Java Virtual Machine specification attempts to define a Java memory model that masks memory access differences between various hardware and operating systems to enable Java programs to achieve consistent memory access across various platforms.
Main memory vs. working memory
The main goal of the Java memory model is to define the access rules for each variable in the program, that is, the underlying details of storing variables in the virtual machine into memory and removing variables from memory. The variables here include instance fields, static fields, and elements that make up the array object, but do not include local variables and method parameters, because the latter is thread-private and will not be shared and there will be no competition issues.
The Java memory model specifies that all variables are stored in the main memory (main memories), that each thread has its own working memory (working memories), that the thread's working memory holds a copy of the main memory of the variable used by the thread, and that all the thread-to-variable operations (read, Assignment, etc.), must be done in working memory, not directly read and write to the variables in main memory. There is no direct access to variables in the other's working memory between different threads, and the transfer of variable values between threads needs to be done through main memory.
Inter-memory interaction operations
The following 8 actions are defined in the Java memory model for the implementation details of the specific interaction protocol between main memory and working memory, i.e. how a variable is copied from main memory to working memory, how to synchronize from the working memory back to main memory, and so on. The virtual machine implementation must ensure that each of the following actions is non-atomic (for variables with double and long types, load, store, read, and write operations allow exceptions on some platforms):
Lock: A variable that acts on the main memory, which identifies a variable as a thread-exclusive state.
Unlock (Unlocked): A variable that acts on the main memory, releasing a variable that is in a locked state, and the released variable can be locked by another thread.
READ: A variable that acts on the main memory, transferring the value of a variable from main memory to the working memory of the thread for subsequent load actions to use.
Load (load): A variable that acts on the working memory, which puts the variable value of the read operation from the main memory into a variable copy of the working memory
Use: A variable acting on a working memory that passes the value of a variable in the working memory to the execution engine, which is performed whenever the virtual opportunity is to a bytecode instruction that needs to use the value of the variable.
Assign (Assignment): A variable acting on a working memory that assigns a variable received from the execution engine to the working memory, and performs this operation whenever the virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.
Store: A variable acting on a working memory that transfers the value of a variable in the working memory to the main memory for subsequent write operations.
Write (): A variable that acts on the main memory, which puts the value of the variable that the store operation obtains from the working memory into a variable of main memory.
If you want to copy a variable from the main memory to the working memory, it is necessary to perform the read and load operations sequentially, if you want to synchronize the variables from the working memory back to the main memory, it is necessary to execute the store and write operations sequentially. The Java memory model requires only that the two operations above must be executed sequentially, without warranty. When accessing A and B in main memory, a possible order is read a, read B, load B, load a.
Special rules for volatile variable types
When a variable defines a bit volatile, it will have two characteristics, the first is to ensure that the variable visibility of all the threads, and the second is to prohibit the command reordering optimization.
Visibility of
When a thread modifies the value of this variable, the new value is immediately known to other threads. However, volatile does not guarantee concurrency security for non-atomic operations such as i++. The volatile variable is suitable for the following two scenarios:
-
The result of the operation does not depend on the current value of the variable, or can guarantee that only a single thread modifies the value of the variable.
-
Variables do not need to participate in invariant constraints with other state variables.
Disable command reordering optimization
From the hardware architecture, the command reordering refers to the use of the CPU to allow multiple instructions, not in accordance with the program specified in the order of development to the corresponding Circuit unit processing but not to say that the instructions arbitrarily reflow, the CPU needs to properly handle the instructions to rely on the situation to ensure that the program can draw the correct results. For example, command 1 adds 10 to the value in address a, instruction 2 takes the value of address a by 2, and 3 of the value in address B 3, when instruction 1 and instruction 2 are dependent, the order between them cannot be re-ordered, but instruction 3 can be re-queued to instruction 1, 2, or the middle.
Atomicity, visibility and ordering atomicity
Atomicity, the basic data type of access read and write is atomic, long and double is the exception, because it is 64-bit, but the vast majority of virtual machines will be atomic implementation, so basically do not consider their non-atomic situation.
Visibility of
Visibility, when a thread modifies the value of a shared variable, other threads can immediately know the change. Volatile, synchronized, and final are all capable of achieving visibility. The visibility of the final keyword is that the final field's value can be seen in the other threads as soon as initialization is completed in the constructor.
Order of
Ordering, the natural ordering of Java programs can be summed up in one sentence: If you observe in this thread, all operations are orderly, and if you look at another thread in one thread, all operations are unordered. The second half of the sentence refers to the "order reordering" and the "synchronous delay between working memory and main memory".
The principle of antecedent occurrence
Happens-before, the following is the natural antecedent relationship of the Java memory model, which can be used directly in the encoding. If the relationship between the two operations is not available or cannot be deduced from the following rules, the virtual machine can reorder them arbitrarily.
-
Sequence rules, program order rule, in a thread, according to the sequence of program code, written in front of the operation of the first occurrence and writing in the back of the operation.
-
The Tube lock rule, Monitor lock, is a unlock operation that occurs after the lock operation that faces the same lock.
-
Volatile variable rule, volatile variable rule, writes to a Volatile variable first occurs after the read operation facing the variable.
-
Thread start rule, thread Star rule, the start () method of the thread object takes precedence over each action of this thread.
-
Thread termination rule, Thead termination rule, all operations in the thread first occur on termination detection of this thread. It is possible to detect that a thread has terminated execution by means of the end of the Thread.Join () method and the return value of thread.isalive ().
-
The thread break rule, thread interruption rule, calls to the thread interrupt () method occur in the code of the interrupted thread to detect the occurrence of the interrupt event, and the Thread.interrupted () method can be used to detect if an interrupt occurred.
-
Object finalization rule, Finalizer rule, the initialization of an object (the completion of a constructor execution) precedes the beginning of its finalize () method.
-
Transitivity, transitivity, if the operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that the operation a first occurs in the Operation C conclusion.
Thread Security Level
In terms of thread-safe security, we can sort data that is shared by various operations in the Java language into the following 5 categories: immutable, absolute thread-safe, relative thread-safe, thread-compatible, and thread-antagonistic.
Not variable
Immutable objects must be thread-safe, regardless of the method implementation of the object or the caller of the method, there is no need to take any further thread security measures. If the shared data is a basic data type, it can be guaranteed to be constant as long as it is modified with the final keyword, and if the shared data is an object, you need to ensure that the object's behavior does not have any effect on its state.
Absolute thread Safety
A class does not require any additional synchronization measures regardless of the run-time environment. It usually takes a lot of time and sometimes it's unrealistic to pay. Labeling yourself as a thread-safe class in the Java API is mostly not an absolute thread-safe. If multiple threads add deletes and reads to a vector at the same time, they may encounter arrayindexoutofboundsexception.
Relative Thread safety
This is the usual sense of thread safety, it needs to ensure that the individual operation of this object is thread-safe, we do not need to make additional safeguards when invoking, but for some specific sequence of successive calls, you may need to use additional synchronization at the caller to ensure the correctness of the call. Most thread-safe classes in Java belong to this type.
Thread compatible
The object itself is not thread-safe, but it is possible to ensure that the object is safe to use in a concurrent environment by using synchronous means correctly at the caller's side. Most of the classes in Java are thread-compatible.
Thread antagonism
Code that cannot be used concurrently in a multithreaded environment, regardless of whether the caller has taken synchronization measures. Very rare and harmful.
Thread-Safe Implementation method Mutex synchronization
(Mutual exclusion & synchronization) is a common method of concurrency correctness assurance. Synchronization is when multiple threads concurrently access shared data, ensuring that shared data is used by only one (or some, use of semaphores) threads at the same time. Mutual exclusion is a means of realizing synchronization, the critical section (Critical), mutex (mutex) and semaphore (Semaphore) are the main mutually exclusive implementations.
Java threads are mapped to the native system of the operating system, and if you want to block or wake up a thread, you need the operating system to do it, which requires a transition from a user state to a kernel mindset, so the state transition takes a lot of processor time. So synchronized is a heavy-weight operation. Reentrantlock is similar to synchronized, but adds some advanced features: Wait for interruptible, fair lock, lock to bind multiple conditions. Fair locking means that when multiple threads are waiting for the same lock, the lock must be acquired one time in the order in which the lock is requested, and the unfair lock does not guarantee this. It is recommended to use synchronized when synchronized is able to meet demand.
Non-blocking synchronization
Mutual exclusion synchronization is also known as blocking synchronization (Blocking synchronization) As long as the problem is a performance issue caused by thread blocking wakeup. In the way of dealing with the problem, the mutex synchronization is a pessimistic concurrency policy, and always think that it will be a problem if you do not do the correct synchronization measures. Optimistic concurrency strategy based on conflict detection is the first action, if no other thread contention shared data, then the operation succeeds, if the conflict, then take other compensation measures (the most common compensation is to continue to re-enable until successful). Many implementations of this optimistic concurrency policy do not need to suspend threads, so this synchronization operation is called non-blocking synchronization (non-blocking synchronization).
Compareandswap (CAS Directive) is an atomic operation at the hardware instruction level.
Deep understanding of Java Virtual Machines-Learning notes-Java memory models and threads