Java Concurrency Summary: multi-thread safe

1. concurrent basis

Definition: a cpu "simultaneously" to handle multiple tasks and multiple threads are competing for this cpu resources

1.1 advantage

Full computing power of multi-core CPU

Split facilitate business, improve application performance

1.2 shortcomings

Frequent context switching time-consuming

Thread-safety issues: atomicity, ordering, reordering

1.3 Related Concepts

Synchronous, asynchronous: each is whether the method is called after the end of the back of the calling code to perform

Concurrent, parallel: the former refers to a cpu time slice by switching the "simultaneous" a plurality of processing tasks; while the latter refers to the true sense, a plurality of CPU

Blocking, non-blocking: If a thread holds a critical resource, then the other threads have to wait for the release of resources in order to continue to perform, then wait for the thread is suspended, that is obstruction; non-blocking contrast, stressed that no one thread can block other threads All threads will attempt to run forward

Critical section: represents one can be used by multiple threads share a common resource or data, when a thread occupy other threads must wait

2. Thread basics

2.1 create a thread way

Inherited Thread, re-run method (limitations: only single inheritance)

Achieve Runable, passed Thread

Achieve callable, submit to the thread pool

2.2 thread state

17130423-54522b8ba69c3195.png!web

State java concurrent threads .png _

NEW acquaintance state is created but not start ()

RUNNABLE operating state (in fact the case in the system can be divided into the scheduling and the READY state RUNNING)

BLOCKED blocked, thread blocks to lock

WAITING waiting transient, waiting for other threads or interrupted notice

TIMED_WAITING wait timeout, the timeout when the waiting time is reached, the thread will switch to state Runable

TERMINATED termination state, the thread is finished

2.3 Basic Operation thread state

2.3.1 stop

Stop the violence, it has been abandoned

2.3.2 interrupt / isInterrupted / interrupted

interrupt: interrupts the thread object, if the thread calls the wait () / wait (long) / sleep () / sleep (long) / join () / join throws InterruptedException when (long) method and clear the flag (thread the interruption can be understood as a flag indicating whether a running thread is interrupted by other threads)

isInterrupted: if this thread is interrupted, the flag is not cleared

interrupted: if this thread is interrupted, the flag is cleared

2.3.3 join

The current thread after only wait to join the process of executing the order to proceed, otherwise it has been blocked

2.3.4 sleep

Sleep, Thread static methods, so that the CPU time slice, will not release the lock, you can call anywhere, sleep time into the end of the thread pool to wait to get the next one resource

2.3.5 wait

After leaving the pool after waiting waiting, Object instance methods, so that the CPU time slice, and release the lock, can only be called a synchronization code, wait for the other thread notify () / notifyAll (), gets the CPU again to continue

2.3.6 yield

Static method, temporarily give up CPU, so that the only time slice allocated to thread priority (priority) the same thread competition

2.4 Daemon daemon thread

By setDaemon (true) daemon thread to the thread, before the method call to set its start ()

Daemon thread ends automatically after the end of a daemon thread, but finally block will not be executed

3.Java memory model (JMM)

When multiple threads access the same objects, if not consider the scheduling of threads in the runtime environment and alternate operation and does not require additional synchronization, or perform any other operation in coordination caller, calling the object's behavior You can get the right result, that this object is thread safe. - "in-depth understanding of the Java Virtual Machine"

Multithreading conditions will involve mutual communication between a plurality of threads; for performance optimization, also relates to a reordering compiler directives and instructions reordering processor issues.

The main reason is the main thread-safe memory and data memory workspace inconsistent understanding of these issues is the core of JMM

3.1 memory model abstract structure

Concurrent programming need to address two main issues, namely communication and synchronization between threads. There are two main mechanisms for communication: shared memory and message passing. Java is selected shared memory approach.

3.1.1 shared variable type

In java program in all instance fields, static fields and array elements are on the heap memory (accessible to all threads, can be shared), and local variables, parameters and methods defined exception handler parameters are not in the thread Room sharing. Data will be shared thread safety issues, rather than the shared data thread-safe without problems.

3.1.2 abstract structure model

Processing speed and main memory read and write speed of the CPU is not an order of magnitude, in order to balance this huge gap, there will be cached for each CPU.

Shared variables are first placed in the main memory, each thread has its own working memory, and will located in main memory shared variables are copied to their working memory, are read and write operations after use variables in the working memory copy, and at some point a copy of the variable working memory is written back to main memory.

If the thread A timely updated data is not written back to main memory, at a time when thread B is read stale data, which appeared in "dirty read" phenomenon.

3.2 reordering

To improve performance, often have compiler and processor instructions reordering; compiler and a processor at the reorder, we will comply with data dependencies, the compiler and the processor does not change the operation of two data-dependent relationship exists execution order

3.3 happens-before

JMM across threads may be provided to assure the visibility of memory by programmers happens-before relation: A thread if the write operation happens-before relation is present between a and b read thread B, although in a different operation and the operation of b thread execution, but JMM to the programmer to ensure that the operation will be a visible operation b

The basic principle: they do not change the results of the program (refer to the program single-threaded and multi-threaded program correctly synchronized), how to optimize the compiler and processor will do. The main rules are as follows:

A program sequence rules: each operation a thread happens-before any subsequent operation to the thread

2 monitor lock (synchronization) rules: a monitor for unlocking, happens-before subsequent locking of the monitor; A thread releases the lock happens-before thread B to lock changes on behalf of the thread A of data threads B visible

3.4 concurrent data security

JMM memory from the abstract structure hehappens-before rules seem, single-threaded case, no data security issues, but multiple threads, data dirty read problem may occur when multiple threads need to develop from atomicity, ordering, visibility three aspects to consider

4Synchronized object locking mechanism

4.1 Synchronized

Synchronization method

// instance method, the instance of the object lock publicsynchronizedvoidmethod class () {}

// static method, the lock publicstaticsynchronizedvoidmethod class is a class object () {}

Sync block

// locked class instance object is synchronized (this) {}

// locked class is the class object synchronized (Object.class) {}

// locked configuration example of an object is synchronized (newObeject ()) {}

Note: If the lock is a class object, then, despite the new multiple instances of objects, but they still belong to the same class will still be locked, that is, to ensure synchronization relationship between threads.

4.2 Object lock mechanism

4.2.1 Java object header

When synchronization to take an object lock is actually acquired the object monitor. monitor similar to a sign of the object, this flag is stored in the object header Java objects. Mark Word advance of the default Java objects in object storage Hashcode, age and generational lock flag.

Monitor is thread-private data structure. Each object will be locked and a monitor associated, at the same time monitor in a store Owner field uniquely identifies the thread that owns the lock, indicating that the lock is occupied this thread.

4.2.2 synchronized to achieve

Modified bytecode file synchronized method, the method is wrapping monitorenter and monitorexit: After synchronization code block must be executed first instruction monitorenter, monitorexit exit command when using Synchronized synchronization, the key is to be subject to monitor monitor be acquired, when the thread gets monitor to continue down, otherwise, they can wait, blocked or block synchronization code synchronization method entry, entered the bLOCKED state.

Data will release the lock when the thread operations are flushed to main memory, main memory will be forcibly taken from the latest value when other threads to acquire the lock

5 Lock

Lock in different ways can be divided into several types, the following summarizes the common classification:

5.1 shared lock exclusive lock VS

Also called exclusive lock exclusive lock means the lock can only be held by a thread. If the thread T A data plus the exclusive lock, other threads can no longer add any A type of lock that only one thread can get the target monitor (monitor) at the same time, while blocking all other threads will get the lock. Acquire an exclusive lock threads that can read data but also to modify the data. JDK in synchronized and Lock JUC in the implementation class is the mutex.

Shared lock means the lock can be held by multiple threads. If the thread T to A plus data shared lock, other threads can only share plus A lock can not add an exclusive lock. Thread acquires a shared lock can only read data, the data can not be modified. As ReentrantReadWriteLock, read lock is a shared lock, write lock is an exclusive lock, its concurrency compared to the general mutex has been greatly improved.

5.2 VS optimistic pessimistic locking lock

For the concurrent operation of the same data, consider themselves pessimistic locking in the use of data must be another thread to modify data, it will first be locked at the time of acquiring the data, ensure that data can not be modified by another thread. The JDK is synchronized and the JUC Lock implementation class.

Optimistic locking think they do not have other threads to modify the data in the use of data, so it will not add locks, just in time before the update data to judge there is no other thread update this data. There are many primarily by lock-free programming algorithm implementations by CAS, Java atomic increment operation on the class implementation class CAS spin implemented using the CAS JUC package.

5.3 spin lock spin lock VS adaptability

Blocking or wake up a Java operating system switching thread needs to complete the CPU state, the state transition takes processor time. If the content of the sync block is too simple, time consuming state transition is likely to be longer than the execution time of the user code.

Make the request lock spin lock thread without giving up the execution time of the CPU, to see if the thread holding the lock will soon release the lock. And can be changed by modifying the maximum number of spin PreBlockSpin, when the lock is to prevent the spin of the time it takes a very long thread waste processor resources

Adaptability spin lock JDK1.6 introduced adaptive mean spin time (number) is no longer fixed, but is locked in a state with a spin lock time and the owner is determined by the previous.

5.4 CASE

5.4.1 Principle

CAS (compare and swap) by comparing the exchange thread to identify whether there is a conflict, the conflict appeared to retry the current operation until there is no conflict. Is understood to be popular CAS (V, O, N), three values ​​are: an actual value V stored in the memory address; new updated value of N; O expected value (old value).

If and only if V is equal to O, CAS manner new value N atom to update the value V ( "+ Comparative Update" is a whole operation atom), or does nothing.

In general, "update" is an ongoing retry attempts.

5.4.2 Problems and Solutions

ABA: If the CAS procedure, an old value to the A to B, and then into A, just do the old value and CAS examination revealed no change still is A, but in fact did change. Solutions can follow common database optimistic locking way, add a version number can be resolved.

Long cycle time spending big. If the CAS operation is not successful for a long time, it can cause it to spin up, to bring a very large CPU overhead.

A shared variable can only guarantee atomic operations: One solution is to use an object to integrate multiple shared variables, namely a class member variable is these shared variables. This object is then done CAS operation can guarantee atomicity. atomic AtomicReference provided to ensure that the object between the reference atom.

5.5 no lock biased locking VS VS VS heavyweight lightweight lock lock

If the content synchronization code block is too simple, time consuming state transition is likely to be longer than the time the user code execution. "This approach is synchronized the initial synchronization of ways, but also the reasons before JDK 6 of synchronized low efficiency. This species dependent on the operating system Mutex lock lock realized we call "heavyweight lock", JDK 6 in order to obtain and release locks reduce performance brought consumption, the introduction of the "biased locking" and "lightweight lock" .

Ahead of Mark Word Java objects recorded four states lock, level from low to high are: no lock, lock biased, lightweight and heavyweight lock lock. Lock state can only upgrade can not be downgraded.

No Lock: no lock no lock on the resources, all the threads can access and modify the same resources, but at the same time only one thread can be modified successfully. CAS theory and application that is lock-free implementation. No lock can not fully replace the lock, but the lock-free performance in some cases is very high.

Biased locking: some synchronization code has been accessed by a thread, the thread ID is stored in the Mark Word in favor of the thread lock automatically acquires the lock, reducing the cost to acquire the lock. Only experience other thread tries to compete biased locking, hold the thread releases the lock will tend to lock, the thread will not take the initiative to release the biased locking.

Lightweight lock: When the lock is biased locking time, be accessed by another thread, it will be upgraded to lightweight biased locking lock, another thread tries to acquire a lock in the form of spin, does not block, thereby improving performance .

Heavyweight lock: When the lock is biased locking time, if the current is only one waiting thread, the thread waits by the spin. But when more than a certain number of spins, or a thread holding a lock, a spin, while another third visit, lightweight heavyweight lock lock escalation. In addition to the thread that owns the lock threads are blocked.

6volatile keyword

6.1 Introduction

Volatile variables can be modified to ensure that each thread can obtain the latest value of the variable, thus avoiding data dirty read phenomenon. Synchronized with respect to the blocking synchronization (thread in a highly competitive situation will be upgraded to heavyweight lock), volatile arguably the most lightweight synchronization mechanism provided by the java virtual machine.

6.2 The principle (cache coherency)

When it will be written in the volatile modification of shared variables when generating assembly code will be more instruction Lock prefix;

Lock prefix instructions cause the processor cache write-back memory;

A processor's cache memory is written back to the other processor's cache can result in failure;

When the processor found in the local cache invalidation, it will re-read the variable data from memory, which can get the most current value.

6.3 happens-before relationship with

Write to a volatile field, happens-before any subsequent read in this volatile field; ensure that each thread can get the latest value, namely "visibility" of the data.

In order to achieve volatile memory semantics, the compiler when generating bytecode will be inserted in the instruction sequence memory barrier to inhibit a particular type of processor reordering. Instruction before the volatile domain operations can not be reordered to operate after volatile domain.

7final keyword

final can be modified variables, methods and classes for representing the modified content will not be changed once the assignment, and this property may be worth changing

7.1 final variable

When the final uninitialized system does not implicitly initialized

7.1.1 final member variables:

Modified class variables (static variables): you must specify an initial value in a static initialization block or specify the initial value when declaring the class variable, and can only be specified in one of two places;

Examples of modified variables (non-static variable): necessary to block the non-static initialization, the instance variables or statements specified initial value in the constructor, and can be specified in three places.

7.1.1 final local variables:

Must be explicitly initialized before use, and has been behind the initialization can not change it again

7.2 final method

Modification methods, the method can not be overridden, can override

7.3 final class

Modified class, the class can not be inherited

And 7.4 final reordering

7.4.1 final basic data types

Write final fields reordering rules: JMM prevent the compiler to write reorder final fields outside the constructor (compiler will write after final fields, constructors return before inserting a barrier storestore)

Read final fields reordering rules: JMM prohibit initial read object references reordering and initial reading final fields two operation of the objects contained, i.e., before reading a target final fields, will first read the object contains the final field references. Actually refers to the presence of the object is read and the final read-targeted indirectly dependent field, a general processor will not reorder the two operations.

7.4.2 final reference data types

Written in the constructor for object a final modification of the member of a domain, and then sends the configured reference object outside constructor assigns a reference variable, these two operations can not be reordered.

Note: The domain of the final write reordering rules can ensure that we use an object reference when the final field of the object has been initialized in the constructor too, that there is a premise: in the constructor can not let this be constructed object is visible to other threads (although final domain before the constructor of an object is initialized return, but if the object referenced by other threads, other threads will lead to yet acquired by the object during the constructor execution the final field is initialized)

More than 800 thread-safety summary

Multi-threading data security, refers to the treatment of multiple threads atomic data, order and visibility problems

8.1 Atomicity

Refers to a operation is not interrupted, either all succeed or all of the failed execution

java memory model defines eight atomic operations: lock (lock), unlock (unlock), read (read), load (load), use (use), assign (assignment), store (store), write ( operating)

Generally it can be considered the basic data types have read and write access atomicity

If we need atomic operations can use a wider range of lock and unlock atomic operations, its main achievement is synchronized

Let volatile guarantee atomicity, must meet the following two rules: Operation result does not depend on the current value of the variable, or be able to ensure that only one thread to modify a variable; variable does not need to participate in other state variables constant constraint

8.2 orderliness

synchronized semantic thread requires only a "serial" executed when the read and write access to shared variables, so have synchronized ordering.

containing semantic volatile disable command reordering, having ordering. There volatile variables, memory barriers around assignment added, not the subsequent instructions to the position before the reordering memory barrier instruction reordering

8.3 Visibility

Get the latest value of the variable will be shared from the main memory when the thread gets the lock, the lock will be released when the shared variable synchronization to the main memory. Thus, synchronized with visibility.

In the volatile, will lock instruction in the instruction by the addition in order to achieve visibility of memory

8.4 summary

synchronized: having atomicity, ordering and visibility;

volatile: a certain order and visibility

Reproduced in: https: //www.jianshu.com/p/007f95307e9e

Guess you like

Origin blog.csdn.net/weixin_34288121/article/details/91163529