Java multi-core thread notes-volatile principles and skills

Source: Internet
Author: User

Volatile, replacing synchronization with a lower cost

Why?Is volatile cheaper than synchronization?
The synchronization cost is mainly determined by its coverage. If the synchronization coverage can be reduced, the program performance can be greatly improved.

Volatile only covers the variable level, so its synchronization cost is very low.

What is volatile?
The volatile semantics tells the processor not to put me into the working memory. Please operate on me directly in the main memory. (For details about the working memory, refer to the Java Memory Model)

Therefore, when multiple cores or threads access the variable, the primary memory is operated directly, which essentially achieves variable sharing.

What are the advantages of volatile?
1. Higher program Throughput
2. Implement multithreading with less code
3. Good program scalability
4. It is easy to understand and requires no high learning costs.

What are the disadvantages of volatile?
1. prone to Problems
2. Difficult to design


Dirty data in volatile operations

Volatile only ensures variable visibility and atomicity.

Volatile Race Condition example:

Public class testracecondition {
Private volatile int I = 0;

Public void increase (){
I ++;
}

Public int getvalue (){
Return I;
}
}

Can I ensure that the value of the increase method increases linearly when multiple threads execute the increase method?
The answer is no.

Cause:
In the increase method, the operation is I ++, that is, I = I + 1;
For I = I + 1, the operation in multiple threads needs to change the I value.
If I has obtained the latest value from the memory but does not perform an operation with 1, other threads have assigned the operation result to I.
When the current thread ends, the previous computation results will be overwritten.

That is, if you run the increase command for 100 times, the result may be <100.
In general, this situation requires a high level of pressure and concurrency.

How can this problem be avoided?
Solution:
One is to add synchronization during the operation.
This method will undoubtedly greatly reduce program performance and violate the original intention of volatile.

The second method is to use the hardware primitive (CAS) to implement non-blocking algorithms.
The CPU primitive supports low-cost synchronization at the variable level.


CPU primitive-compareandset to implement non-Blocking Algorithms

What is Cas?
CAS is the primitive operation that modern CPUs provide to concurrent programs. Different CPUs have different usage specifications.

In Intel processors, the cmpxchg series of commands are compared and exchanged.
The PowerPC processor has a pair of commands named "load and retain" and "Conditional storage", which implement the same purpose;
MIPs is similar to the PowerPC processor, except for the first command called "load link ".

The CAS operation contains three operands: memory location (V), expected original value (A), and new value (B)

What is a non-blocking algorithm?
Failure or suspension of a thread should not affect the failure or suspension of other threads. Such algorithms are called non-blocking algorithms.

Comparison of Blocking Algorithms:
If there is a type of concurrent operation, one of the threads gets the lock of the object monitor first, and when other threads reach the synchronization boundary, it will be blocked.
The competition for Object locks can continue until the previous thread releases the lock (of course, the competition here is fair, in the order of first come and then)

CAS principle:

I think location V should contain the value A. if it contains the value, place B in this location. Otherwise, do not change this location. Just tell me the current value of this location.

Example of CAS usage (JDK 1.5 and atomicinteger Class Analysis :)

/**
* Atomically sets to the given value and returns the old value.
*
* @ Param newvalue the new value
* @ Return the previous value
*/
Public final int getandset (INT newvalue ){
For (;;){
Int current = get ();
If (compareandset (current, newvalue ))
Return Current;
}
}

Public final Boolean compareandset (INT exact CT, int update ){
Return unsafe. compareandswapint (this, valueoffset, exact CT, update );
}

This method is a common method of the atomicinteger class. It sets the variable to a specified value and returns the value before the setting.
It uses the CPU primitive compareandset to ensure the uniqueness of the value.

In addition, in the atomicinteger class, other practical methods are also based on the same implementation method.
For example, getandincrement, getanddecrement, and getandadd.

CAS"ABA problem"

What is ABA?
Assume that the first read of the value a of the V address, and then use CAs to determine whether the value of the V address is still a. If yes, the value B is written to the V address to overwrite the value.

However, in terms of semantics, there is a vulnerability. When a value of V is read for the first time, the value of memory V Changes to B, and then the value of A is changed back Before Cas is executed.
When CAS is executed again, it will judge the correctness and assign values.

This method determines whether the memory has been modified. It is not applicable to some problems.

To solve this problem, JDK 1.5 providesAtomicStampedReference(Labeled atomic reference) class, ensures the correctness of CAS by controlling the version of the variable value.

In fact, CAS is sufficient for most of the changes in values.

Introduction to the jdk1.5 atomic package (based on volatile)

Package features:
1. atomicinteger and atomiclong provide addition and subtraction operations for atomic operations.

2. Use the Classic mode to solve the dirty data problem-"set after comparison" to check whether the data in the primary storage is consistent with the expected value. If the data is consistent, it is updated.

3. atomicreference can be used to reference and assign values to all objects, including double and float,
But it does not include the calculation of its floating point. It can only be achieved by the synchronous keyword or lock interface.

4. For objects in array elements that comply with the preceding features, atomic operations can also be used. Some array atomic operations are provided in the package.
Atomicintegerarray, atomiclongarray, etc.

5. Greatly improve system throughput and performance.

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.