JAVA-- memory model and thread-safe

Java Memory Model

In order to solve the great differences between CPU speed and physical memory read and write speed, Java introduces the concept of cache, cache read and write speed and CPU speed almost. I.e., working memory and the main memory, the main memory corresponding to the actual physical memory, each thread has its own working memory, all data stored in the main memory, data to be used are thread from the main memory copy of the data, until completion of return processing data written to main memory.

Why is there a thread safety issues

We know that the data from the copy of thread operations are the main thread, when multiple threads access the same data, it may occur when a thread is reading data another thread has not had time to be written to main memory, resulting read is dirty, that's my understanding of thread safety issues

How to determine whether an action is a thread-safe

Java custom first principles eight kinds occur

  • Program sequence principle: with internal thread, EDITORIAL code always occurs first in the code behind
  • Lock principle: unlock operation on a lock after the first occurrence in the face with a lock of lock operation
  • Volatile variable principle: Volatile write to the first modification of variables occurs after facing variable read
  • Thread starts principles: thread start () method first occurred in the threads of all other operations
  • Thread terminates principles: first thread all other operations occur in the thread termination operations
  • Object terminate principles: initial completion of finalize occurred in the first object () method call
  • Transitivity: A B occurred first, B C occurs first, then A first occurrence C

If an operator does not directly meet those principles, and can not be deduced from these principles, then it is not thread-safe

Volatile keyword

Volatile modified variable has two properties

  • Visibility, write a Volatile variable, the value of working memory will sync back to main memory, read a Volatile variable, will set the value of the worker thread to be invalid
  • Sequential, Volatile keyword disallowed instructions ordering

How to solve thread safety issues

To guarantee thread safety is to ensure that operations meet three characteristics

  • Atomic: a completed operation so, then do not perform, without interruption (ie number of performed some not performed) operation, basic data types and reading assignments are atomic operations

  • Visibility: working memory operations will immediately synchronized to the main memory, that is operating a thread immediately visible to all other threads

  • Ordering: JVM can reorder instructions, but no matter how sort, to ensure that the same results of program execution

Through the front may know, Volatile keywords can ensure visibility and orderliness 如果对Volatile关键字修饰的变量操作也具备原子性的话, it is thread-safe. So it is a lightweight thread-safe mechanism

Use keywords and principles Synchronized

Synchronized keyword can ensure that the operator has three characteristics

It will increase before and after the compiled code Monitorenter and Monitorexit two instructions, this instruction has a reference attribute, used to develop object needs to lock and unlock, except when explicitly lock object, otherwise Synchronized modification of the general method is to lock objects object instance, when the lock object is a method for modifying the static class object class

// It should be clearly understood then change

When the thread execution Monitorexit instruction, will try to get the object's lock, if the acquisition fails, the object is locked, thread blocking. Otherwise, the object is locked, the counter is incremented by 1

ReentrantLock

And contracting under the reentrant thread lock may be used to achieve synchronization, the need to explicitly perform unloc lock operation and use, and with a try / finally to ensure that the unlocking operation can be performed in any case, and it provides more advanced Features

  • Wait for interruptible: If a thread waiting to acquire the lock time is too long, you can choose to give up waiting
  • Fair locks, allowing the thread queue in chronological order in order to obtain a lock application lock, use lockInterruptibly () method
  • Binding a plurality of conditions, with the use condition, use newConditin () method

Lock optimization

JDK5 ago, Synachronized and ReentrantLock have a big difference in performance, but after JDK6, almost no performance difference compared to Synachronized done a lot of optimization, and ReentrantLock, it is recommended under normal circumstances, after all, very easy to use Synachronized

  • Spin thread to lock into the blocked state is to achieve a major performance cost of synchronization, because the thread should switch from user mode to kernel mode. Spin lock is not directly block the thread, but performs a loop, waiting to enter the busy state, the default cycle 10 times, if after 10 cycles has not yet acquired the lock, and then blocked thread

  • Spinlock adaptive adaptation cycles are not provided, but a lock time is obtained in accordance with the conditions such as the number of cycles of the automatic setting

  • Lock coarsening and so on ...

Guess you like

Origin juejin.im/post/5d751355f265da03ba32665c