Overview
In order to resolve the speed contradiction between memory and CPU, we introduced a cache of write speed as close to CPU as possible before both: copying the data needed to the operation into the cache, allowing the operation to be done quickly, and then synchronizing back to memory from the cache when the operation is finished, so that processing does not have to wait for the slow memory to read and write.
But this also brings a higher degree of complexity to the computer system because it introduces a new problem: cache consistency. In a multi-processing system, each processing has its own cache, and they share the same main memory, and when the operations of multiple processors involve the same chunk of main memory, they may cause their cache data to be inconsistent.
Memory model: It can be understood that the process of reading and writing access to specific memory and caches is abstracted under a specific operating protocol. Physical machines of different architectures can have dissimilar memory models, and Java virtual machines have their own memory models.
The Java Memory model (MODEL,JMM) is a memory model built up from jdk1.2 and completed in jdk1.5. 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. C, C + + and other direct use of force hardware and operating system memory model, due to different platform memory model differences, resulting in the program can not be a perfect transplant.
Main memory and working memory
The main goal of the Java memory model is to define access rules for variables in the program, that is, the underlying details of storing variables into memory and removing variables from memory in the virtual machine. This is different from the variables described in Java programming, which include instance fields, static fields, and elements that make up the array object, but not local variables and method parameters (thread-private, not shared, no competition)
The Java memory model specifies that all variables are stored in the main memory. Each thread also has its own working memory (the working memory), which holds the master memory copy of the variables used by the thread, and all operations of the thread on the variable (read, assign, etc.) must be made in working memory and not directly read and write to the variables in main memory. There is no direct access to the variables in the other's working memory between different threads, and the thread's delivery of variable values needs to be done through main memory.
Here the main memory and working memory and Java memory area in the Java heap, stack, method area and so on is not the same level of memory division.
The specific interaction protocol between main memory and working memory: How a variable is copied from the main memory to the working memory, if the implementation details are synchronized back to the main memory from the working memory.
The Java memory model is scheduled to complete in 8, and the virtual machine must ensure that each operation is atomic and non-divided:
(1) Lock: Lock, make a variable for the main memory, it identifies a variable as a thread exclusive state;
(2) Unlock: Unlock, for the main memory of the variable, it will be locked in a variable release, the released variable can be locked by other threads;
(3) Read: reads, acts as a variable for the main memory, which transfers the value of a variable from the main memory to the working memory of the thread for subsequent load actions to be used;
(4) Load: Load, as a variable for working memory, which puts the value of a read operation from memory into a variable copy of the working memory;
(5) Use: Used as a variable in the working memory, it passes the value of a variable in the working memory to the execution engine, which will be executed whenever the virtual opportunity becomes a worthwhile bytecode instruction that needs to be used to the variable;
(6) Assign: assignment, as a variable for working memory, which assigns a variable received from the execution engine to the working memory, and performs this operation whenever the virtual opportunity is to a byte-code instruction that assigns a value to a variable;
(7) Store: A variable used for working memory, which transfers the value of a variable in the working memory to the main memory for subsequent write operations;
(8) Write: Writes the variable that is used for 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 main memory to working memory, then perform the read and load operations sequentially, and if you synchronize the variables from the working memory back to the main memory, store and write operations will be performed sequentially.
The Java memory model also fixed the rules that must be met when performing 8 basic operations:
(1) One of the read and Load,store and write operations is not allowed to appear separately;
(2) A thread is not allowed to discard its most recent assign operation, that is, the variable must be synchronized back to main memory after it has changed in working memory;
(3) A thread is not allowed to synchronize data from the working memory back to main memory without a reason (no assign operation has occurred);
(4) A new variable can only be "born" in main memory;
(5) A variable allows only one thread to lock it at the same time, and can be executed repeatedly by the same thread;
(6) More than one variable performs a lock operation, which empties the value of this variable in the working memory, and needs to re-execute the value of the load or assign operation initialization variable before the execution engine uses the variable;
(7) If a variable is not locked by lock in advance, it is not allowed to execute unlock on him or to unlock a variable locked by another thread;
(8) before performing a unlock operation on a variable, you must first synchronize this variable back into main memory
Volatile
Volatile has two characteristics: (1) Ensure that this variable disables command reordering optimizations for all thread visibility (2).
The volatile variable has no consistency in the working memory of the spec thread: in the working memory of the spec thread, volatile variables can also be inconsistent, but because the execution engine does not see inconsistencies before each use, it can be considered that there is no inconsistency. But the operation in Java is not atomic, and the operation of the volatile variable is as insecure as it is in concurrency.
Atomicity, Visibility and orderliness
The Java memory model is built around the 3 characteristics of how atomicity, visibility, and ordering are handled in a concurrency process.
(1) atomicity: the Java memory model to directly guarantee the operation of atomic variables including read,load,assign,use,store,write;
The bytecode directives for the lock and unlock operations are monitorenter and Monitorexit, and the response to the Java code is the synchronization block--synchronized keyword, so the operation between the synchronized blocks is also atomic.
(2) Visibility: When a thread modifies the value of a shared variable, other threads can immediately be informed of the change. The Java memory model realizes visibility by synchronizing the new values back to main memory after the variable is modified, and by refreshing the variable value from the main memory before the variable is read, which relies on the main memory as the medium of delivery, regardless of the normal variable or the volatile variable. The difference between a normal variable and a volatile variable is that the special rules for volatile ensure that the new value is immediately synchronized to the main memory and flushed from the main memory immediately before each use. Thus, it can be said that volatile guarantees the visibility of variables in multi-threaded operations, while ordinary variables do not guarantee this.
(3) Order: The Java language provides volatile and synchronized two keywords to ensure the order of operations between threads.
The principle of antecedent occurrence
(1) Procedural order rules
(2) Tube lock rule
(3) volatile variable rules
(4) thread start rule
(5) Thread termination rules
(6) Thread break rule
(7) Object End rule
(8) transitivity
An operation "in the first place" does not mean that the operation will be "antecedent", an operation is "first occurrence" or not necessarily "time occurs".
When measuring concurrency security issues, do not be disturbed by chronological order, and everything must be based on the principle of antecedent occurrence.
Implementation of Threads
There are 3 main ways: (1) using kernel thread implementation (2) using User thread implementation (3) using User line loads lightweight process hybrid implementation
(1) Kernel thread: a thread that is supported directly by the operating system (kernel, kernel), which is thread-switched by the kernel, and the kernel dispatches the thread by manipulating the scheduler and is responsible for mapping the thread's task to the specification processor. Instead of using kernel threads directly, use a high-level interface of kernel threads-lightweight processes.
(2) User thread: Broadly, a thread can be considered a user thread as long as it is not a kernel thread , and from this definition, a lightweight process is also a data user thread. In the narrow sense, a user thread is an implementation that is completely built on the user control's line libraries, and the system kernel cannot perceive the thread's existence.
(3) User line loads lightweight process blending: The first two kinds of mixing. In this hybrid implementation, there is a user thread, there is also a lightweight process, the user thread is completely built in user space, so the user thread creation, switching, destruction and other operations are still cheap, and can support large-scale user thread concurrency. While the lightweight process supported by the operating system serves as a bridge between the user thread and the kernel thread, it can use the thread scheduling and processor mappings provided by the kernel, and the user thread's system calls are done through a lightweight process, greatly reducing the risk of the entire process being completely blocked.
Java Threading Implementation
(1) Implementation: From jdk1.2, the threading model is replaced by the OS native threading model. The threading model supported by the operating system largely determines how the Java virtual machine threads are mapped, and there is no way to agree on different platforms, and the virtual machine specification does not qualify which threading model the Java thread needs to implement. The threading model affects only the concurrency and operating costs of threads, and these differences are transparent to the code and operation of the Java program.
Sun jdk its Windows and Linux versions are implemented using a one-to-one threading model, and a Java thread maps to a lightweight process.
(2) refers to the system for the thread to assign the process of the use of the processor, the main scheduling methods have two kinds: (A) cooperative thread scheduling (B) preemptive thread scheduling, Java uses the scheduling method is preemptive scheduling.
(3) Reload conversion
- NEW: A thread that has not been started since it was created
- Run: A thread in this state may be executing, or may be waiting for the CPU to allocate execution time to it
- Infinite wait: will not be allocated CPU execution time, waiting to be Cheng by other lines, such as object.wait (), Thread.Join (), Locksupport.park ()
- Limited wait: The timeout can be automatically awakened by the system. such as Thread.Sleep (), object.wait (Long), Thread.Join (Long), Locksupport.parknanos (), Locksupport.parkuntil ()
- Block: A blocking state is a waiting time to acquire an exclusive lock; a wait state is the occurrence of a waiting period or a wake-up action.
- End: Terminated.
Thread Safety
Definition: When multiple threads access an object, it is not necessary to take into account the scheduling and alternation of these threads in the run-time environment, the need for additional synchronization, or any other coordinated operation by the caller, the behavior of invoking the whole object can obtain the correct result, the whole object is thread-safe.
How to implement thread safety
Resources
Deep understanding of Java Virtual machines: JVM advanced Features and Best Practices (second edition)
Multithreading-java memory Models and threads