In layman's Java Concurrency (5): Atomic operation part 4[go]

Source: Internet
Author: User
Tags cas

Prior to JDK 5, the Java language was guaranteed to be synchronized by the Synchronized keyword, which would result in a lock (later chapters will also talk about locks).

The lock mechanism has the following issues:

(1) Under the multi-thread competition, the locking and release lock will lead to more context switching and scheduling delay, causing performance problems.

(2) A thread holding a lock causes all other threads that require this lock to hang.

(3) If a high-priority thread waits for a thread with a lower priority to release the lock, it causes the priority to be inverted, causing a performance risk.

Volatile is a good mechanism, but volatile does not guarantee atomicity. Therefore, for synchronization to eventually return to the lock mechanism.

An exclusive lock is a pessimistic lock, and synchronized is an exclusive lock that causes all other threads that need to be locked to hang, waiting for the thread that holds the lock to release the lock. Another more effective lock is the optimistic lock. The so-called optimistic lock is that each time without locking but assuming that there is no conflict to complete an operation, if the conflict failed to retry until successful.

CAS operations

The mechanism used for optimistic locking above is cas,compare and Swap.

CAS has 3 operands, a memory value of V, an old expected value of a, and a new value to be modified B. If and only if the expected value A and the memory value of the V phase, the memory value of V is modified to B, otherwise do nothing.

Non-blocking algorithm (nonblocking algorithms)

Failure or suspend of one thread should not affect other threads ' failed or suspended algorithms.

Modern CPUs provide special instructions to automatically update shared data and detect interference from other threads, and Compareandset () replaces the lock with these.

Take out Atomicinteger to study how the data is correct without a lock.

private volatile int value;

First of all, in the absence of a lock mechanism may require the use of volatile primitives, to ensure that data between threads is visible (shared).

This allows the value of the variable to be read directly when it is obtained.

Public final int get () {
return value;
}

Then let's see how ++i did it.

Public final int Incrementandget () {
for (;;) {
int current = get ();
int next = current + 1;
if (Compareandset (current, next))
return next;
}
}

The CAS operation is used here, each time the data is read from memory and then the CAS operation is performed with the result of +1, if successful, the result is returned, otherwise it is retried until it succeeds.

Instead, Compareandset uses JNI to perform the operation of the CPU instructions.

Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}

The whole process is like this, using the CPU's CAS instruction, and using JNI to complete the Java non-blocking algorithm. Other atomic operations are done using a similar feature.

And the whole j.u.c is built on the CAs, so for synchronized blocking algorithm, J.U.C has a great improvement in performance. The resources article describes the use of CAs to build data structures such as non-blocking counters, queues, and so on.

CAS looks cool, but it can cause "ABA problems".

The CAS algorithm implements an important premise that needs to take out the data at some point in memory, and compare and replace at the next moment, then the time difference class will cause the data to change.

For example, a thread one takes a from the memory location V, when another thread two also takes a from memory, and two does something to B, and two then turns the data in the V position into a, when the CAS operation finds that the memory is still a, and then the one operation succeeds. Although the CAS operation of thread one is successful, it does not mean that the process is not a problem. If the head of the list is changed two times, the original value is restored, but the list does not change. So the atomic operation Atomicstampedreference/atomicmarkablereference mentioned earlier is very useful. This allows a pair of changed elements to operate atomically.

Resources:

(1) Introduction to non-blocking algorithms

(2) Popular atoms

In layman's Java Concurrency (5): Atomic operation part 4[go]

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.