Java memory model and volatile, synchronized

Foreword

  1. First talk cache computer: a computer when executing the program, are performed by the CPU instructions, of course, ultimately, the implementation of a series of instructions need certain data, the data in the main memory (physical memory). With the development of science and technology, CPU execution speed faster and faster, but the memory access development has not kept pace with the rapid development of CPU, cause performance bottlenecks appeared in the memory access, so this time there have been caching technology to speed up data access.
  2. Actually running the program, the data will require calculation of a main memory copied from the cache to the CPU which, so the CPU can be calculated directly from its cache read and write data, when the end of the operation, and then high-speed data in the cache are flushed to main memory them.
  3. But when there is a multi-core CPU, there is a cache on each core, and are likely to run the thread, the thread is concurrent, they will modify the cache where their nuclei in the variable, it will lead to data inconsistencies.

Atom, visibility, orderly

  1. Atomicity refers to a cpu operation is not suspended in the middle and then scheduling neither operation is interrupted, or executed, or do not execute. - Processor Optimization will lead to atomic problems
  2. Visibility means that when multiple threads access the same variable, a thread changes the value of this variable, other threads can immediately see the modified values. - cache coherency
  3. I.e. sequential ordering of execution program executed according to the order code. - instruction rearrangement leads to ordering problems
  4. How to achieve the above mentioned three characteristics do? => This is the Java memory model to solve the problem

Java Memory Model - JMM

  1. Java memory model specifies all the variables are stored in main memory, each thread also has its own working memory, working memory threads in the thread is stored in main memory copy of a copy of Shidao variables, variable thread All operations must be carried out in the working memory, but can not directly read and write main memory.
  2. Between different threads can not directly access the working memory of the other variables, the variables are passed between threads require data between their working memory and main memory simultaneously. So, the situation changed thread 1 value of a variable, but invisible thread 2 may occur.
  3. JMM while it acts on the data synchronization process between the working memory and the main memory. He sets out how to do and when to do data synchronization data synchronization
  4. Therefore, JMM is a specification for solution since the multi-threaded communication, local memory data inconsistency exists through shared memory, the compiler will reorder code instructions, the processor would be out of order execution code is brought problem.
  5. Java memory model defines a set of specifications in addition, also provides a series of primitives (volatile, synchronized, final, concurrent packet), encapsulates the underlying implementation, were developed for direct use.

volatile

  1. Use volatile variables can be modified after it has been modified can be synchronized to the main memory immediately, by its modified variables are flushed from main memory before each use. Therefore, you can use volatile to ensure the visibility of multi-threaded operation variables.
  2. volatile can only ensure the orderly and visibility.

synchronized

  1. synchronized ensure atomicity, ordering and visibility.
  2. Scope:
  3. Acting on common method
  4. Acting on the static method
  5. Acting on the block
  6. Only call wait / notify methods in synchronized block or method
  7. Range:
  8. When the method of modifying the time, which act only on the present object instance
  9. When modifying the static method, applied to the object class (static method of the present fall into this category, it can be on any class)
  10. When the modified code block, or whether the object instance
  11. Here again extend explore how synchronized is to ensure atomicity of it? This first talk about how the Java virtual machine perform thread synchronization in the

How to perform thread synchronization in Java Virtual Machine

  1. In Java memory structure, there are two areas will be shared by all threads - the method area (store static variables) and heap (store all object instances), so as to achieve shared the same object should be multiple threads change. To achieve these changes would require Java virtual machine management and control.
  2. So virtual machine for each object class and have added a lock, when a thread is going to change the subject and they will lock the whereabouts of a virtual machine application (virtual machine may be delayed to lock), access to the lock thread the object to be modified, then after the lock back to the virtual machine, the virtual machine and thread allocation for the next lock.
  3. Which lock to the class, in fact, by giving object locking achieve, because each time class load, there will be an instance of java.lang.Class, give this instance lock is achieved.
  4. Monitor (Monitors): JVM locks is through something called the monitor to achieve, monitor for monitoring a piece of code to ensure that only one thread at the same time executing it.
  5. Each of the monitors associated with one of the segment like when you start to run this code, the thread must acquire the lock objects it references. Once locked, the thread can enter the "protected" code started. When a thread leaving the code block, in any case leave, will release the lock associated with the object.

synchronized implementation principle

  1. Each object has a lock monitor (monitor). When the monitor is occupied will be in a locked state, attempt to acquire ownership of the monitor thread execution monitorenter command, as follows:
    1. If the number entering the monitor is 0, the thread enters the monitor, and then enter the number is set to 1, the thread is the owner of the monitor.
    2. If the thread has occupied the monitor, only to re-enter, then enter the number into the monitor plus one.
    3. If another thread has occupied the monitor, the thread enters the blocked state into the monitor until the number is zero, then re-attempt to obtain ownership of the monitor.
  2. Monitorexit thread of execution must be objectref corresponding monitor owners.
    1. When the instruction is executed, enter the monitor number minus 1, minus 1 if entered number is 0, then the thread exits monitor, it is no longer the owner of this monitor. Other threads are blocked this monitor can attempt to take ownership of this monitor.
  • This is the principle of synchronized synchronized block, as well as synchronization method is implemented by ACC_SYNCHRONIZED mark, to be specific supplement ...

And finally back to synchronized is how to ensure the atomic issue

Such as thread 1 in the implementation of monitorenter instructions, Monitor will be locked after locking the other threads can not get a lock, unless the thread 1 active unlocked. Even in the implementation process, for some reason, such as CPU time slice runs out, he gave up the thread 1 CPU, but he did not unlock. And because synchronized locks are reentrant, or the next time slice can only get to by his own, or will continue to execute code. Until all the code executed. This ensures atomicity.

Reference article

how-the-java-virtual- machine-performs-thread-synchronization time someone asks you what Java memory model that put the article issued to him. The principle of Synchronized

Guess you like

Origin juejin.im/post/5d6a0674f265da03db078f68