Java concurrency Features: atomicity, visibility, ordering

Source: Internet
Author: User
Tags volatile

In order for concurrent programs to execute correctly, atomicity, visibility, and ordering must be ensured. As long as one is not guaranteed, it may cause the program to run incorrectly.

1. atomicity (atomicity)
Atomicity means that in one operation the CPU is not allowed to pause and then dispatch, neither interrupted nor executed.

If an operation is atomic, then multiple threads are concurrent, there is no case that the variable is modified

such as A=0; (a non-long and double type) This operation is indivisible, then we say this operation is atomic operation. Another example: a++; This operation is actually a = a + 1; is divisible, so he is not an atomic operation.

There is a thread-safety problem with non-atomic operations, and we need to use synchronous technology (sychronized) to turn it into an atomic operation. An operation is an atomic operation, so we call it atomic. The Java concurrent package provides some atomic classes, and we can read the API to understand the use of these atomic classes. For example: Atomicinteger, Atomiclong, atomicreference and so on.

(Atomic variable operations, directly guaranteed by the Java memory model, include read, load, use, assign, store, and write six, which can roughly be considered atomic for access and read-write of the underlying data type.) If the scenario requires a wider range of atomicity guarantees, the Java memory model also provides lock and unlock operations to meet this requirement, although the virtual machine does not open lock and unlock operations directly to the user, But it provides a higher level bytecode directive Monitorenter and monitorexit to use these two operations in stealth, the two bytecode instruction is reflected in Java code is the synchronization block-synchronized keyword, Thus the operation between the synchronized blocks is also atomic. )

2. Visibility (Visibility)

Visibility means that when a thread modifies the value of a thread-shared variable, other threads can immediately know 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 values from the main memory before the variable is read, which relies on the main memory as a means of transmitting the media, whether it is a normal variable or a volatile variable. The difference between a normal variable and a volatile variable is that the special rule of volatile guarantees that the new value can be immediately synchronized to the main memory and flushed from memory immediately before each use. Because we can say that volatile guarantees the visibility of variables when threading, while normal variables do not guarantee this.

In addition to the volatile, Java has two keywords to achieve visibility, they are synchronized. The visibility of a synchronization block is obtained by synchronizing this variable back into main memory (performing store and write operations) before performing a unlock operation on a variable, while the final keyword's visibility means that the final-modified field is the constructor once initialized And the constructor does not pass the "this" reference, the value of the final field can be seen in other threads.

(visibility, which refers to the visibility between threads, the state of a thread modification is visible to another thread.) That is, the result of a thread modification. Another thread can see it right away. For example: variables modified with volatile will have visibility. Volatile-modified variables do not allow the thread to cache and reorder internally, that is, to modify memory directly. So it is visible to other threads. But there is a problem to be aware of, and volatile can only make it visible to the content he modifies, but it does not guarantee that it is atomic. For example, volatile int a = 0, then there is an operation a++, this variable a has visibility, but a++ is still a non-atomic operation, and this operation also has a thread safety problem. )

3, Order (ordering)

The natural ordering of the programs in the Java memory model can be summed up in one sentence: If you observe in this thread, all operations are orderly, and if you observe another thread in one thread, all operations are unordered. The first half of the sentence refers to "line range performance as serial semantics", the latter sentence refers to the "order reordering" phenomenon and "the main memory synchronization delay in working memory" phenomenon.

The Java language provides the volatile and synchronized two keywords to ensure the ordering of operations between threads, and the volatile keyword itself contains the semantics of prohibiting command reordering, while synchronized is the " A variable that allows only one thread to lock on it at the same time "this rule determines that two synchronized blocks holding the same lock can only be entered serially.

The principle of antecedent occurrence:

If all the ordering in the Java memory model is done only by volatile and synchronized, then some of the operations will become verbose, but we do not feel this when writing Java concurrency code because there is an "antecedent" in the Java language ( Happen-before) principle. This principle is very important, it is the main reliance to judge whether the data is competitive and whether the thread is safe or not.

The first occurrence principle refers to the sequential relationship between two operations defined in the Java memory model, and if operation a precedes operation B, it is said that the effect of operation A can be observed by Operation B before Operation B, "Impact" includes modifying the values of shared variables in memory, sending messages, calling methods, etc. What does it mean? The following example:

Execute in Thread A
i = 1;

Executed in thread B
j = i;

Execute in thread C
i = 2;
Assuming that the operation "I=1" in thread a precedes the operation "j=i" of thread B, then we can determine that the value of the variable J must be equal to 1 after the operation of Line B, and that the basis for this conclusion is two, and that the results of the "i=1" can be observed in accordance with the principle of antecedent occurrence. The second is that no other thread will modify the value of the variable i until thread C has finished. Now consider thread C, we still maintain the antecedent relationship between threads A and B, and thread C appears between the thread A and B operations, but C and B do not have a prior relationship, then the value of J may be 1, or 2, because the impact of thread C corresponding to the variable I may be observed by thread B, or may not be observed, At this point, thread B has the risk of reading to outdated data, without the security of multithreading.

The following are some of the "natural" antecedent relationships in the Java memory model, which are already present without any Synchronizer assistance and can be used directly in the encoding. If the relationship between the two operations is not there and cannot be deduced from the following rules, they are not guaranteed to be sequential, and the virtual machine can reorder them arbitrarily.

A. Order of Procedure rules (pragram Order rule): In a thread, according to the sequence of program code, the preceding operation precedes the operation that is written in the back. It should be accurate to control the flow order rather than the program code order, because the branching and looping structures are considered.

B. Tube lock rule: A unlock operation first occurs after the lock operation facing the same lock. The same lock must be emphasized here, and the "back" refers to the chronological order of the time.

C.volatile variable rules (volatile Variable rule): Write to a volatile variable precedes the read operation of the variable, where the "back" also refers to the chronological order.

D. Thread start rule: the Start () method of the thread object takes precedence over each action of this thread.

E. Thread finally rule (thread termination rule): All operations in the thread occur first in the termination detection of this thread, we can end with the Thread.Join () method, Thread.isalive () The return value of such a segment detects that the thread has terminated execution.

F. Thread interruption rule: the invocation of the thread interrupt () method first occurs when the code of the interrupted thread detects that the interrupt event occurred, and can be passed thread.interrupted () method to detect if an interrupt occurred.

G. Object termination rule (Finalizer rule): An object initialization completes (the construction method execution completes) first occurs at the beginning of its finalize () method.

G. transitivity (transitivity): If operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that operation a precedes operation C.

An operation "time first" does not mean that the operation will be "antecedent", then if an operation "first occurrence" whether it can be deduced that the operation must be "time to occur"? is also not tenable, a typical example is the order reordering. Therefore, the order of time and the principle of the occurrence of a basic relationship between, so the measurement of concurrency security must be based on the principle of first occurrence.

Original address:

51442192

Java concurrency Features: atomicity, visibility, ordering

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.