Java concurrent programming (8) atomic variables and non-blocking synchronization mechanisms, java Variables

Source: Internet
Author: User

Java concurrent programming (8) atomic variables and non-blocking synchronization mechanisms, java Variables
Atomic variables and non-blocking synchronization mechanisms I. disadvantages of locking

1. In multithreading: there is a great deal of overhead in the Process of lock suspension and restoration (modern jvm will judge when to use suspension and when to spin wait)

2. volatile: lightweight synchronization mechanism, but cannot be used to build atomic composite operations

Therefore, there must be a more fine-grained approach in the competition between management threads, similar to the volatile mechanism and atomic update operations.

Ii. CAS

An exclusive lock is a pessimistic technique-it assumes the worst case, so each thread is exclusive.

CAS compares and exchanges: compareAndSwap/Set (A, B): We think the value of memory is A. If it is A, change it to B. Otherwise, no operation is performed; returns the original value in the memory or whether the modification is successful.

For example, simulate CAS operations

// Simulate CASpublic class SimulatedCAS {private int value; public synchronized int get () {return value;} // CAS Operation public synchronized int compareAndSwap (int expectedValue, int newValue) {int oldValue = value; if (oldValue = expectedValue) {value = newValue;} return oldValue;} public synchronized boolean compareAndSet (int expectedValue, int newValue) {return (expectedValue = compareAndSwap (Objective C TedValue, newValue) ;}// typical use cases: public class CasCounter {private SimulatedCAS value; public int getValue () {return value. get () ;}public int increment () {int v; do {v = value. get () ;}while {(v! = Value. compareAndSwap (v, v + 1);} return v + 1 ;}}

 

JAVA provides CAS operations

Atomic State Class: CAS method of AtomicXXX

Java 7/8: Map operations: putIfAbsent, computerIfAbsent, computerIfPresent .........

Iii. atomic variables

AtomicRefence: An atomic update object, which can be a custom object. For example:

Public class CasNumberRange {private static class IntPair {// INVARIANT: lower <= upper final int lower; // defines the value as an immutable domain final int upper; // defines the value as an immutable domain public IntPair (int lower, int upper) {this. lower = lower; this. upper = upper ;}} private final AtomicReference <IntPair> values = new AtomicReference <IntPair> (new IntPair (0, 0); // encapsulate object public int getLower () {return values. get (). lower;} public int getUpper () {return values. get (). upper;} public void setLower (int I) {while (true) {IntPair oldv = values. get (); if (I> oldv. upper) {throw new IllegalArgumentException ("Can't set lower to" + I + "> upper");} IntPair newv = new IntPair (I, oldv. upper); // if the attribute is an immutable domain, the newly created object if (values. compareAndSet (oldv, newv) {// atomic update. If a thread is modified during the process, other threads are not updated successfully, because the oldv and memory values are different, return; }}// same as public void setUpper (int I) {while (true) {IntPair oldv = values. get (); if (I <oldv. lower) throw new IllegalArgumentException ("Can't set upper to" + I + "<lower"); IntPair newv = new IntPair (oldv. lower, I); if (values. compareAndSet (oldv, newv) return ;}}}

 

Performance problems: the use of atomic variables in low concurrency (competition), faster than the use of lock speed, generally faster than the lock speed

 

Iv. Non-Blocking Algorithms

Non-Blocking Algorithms can be used in many common data structures.

Non-Blocking Algorithm: in multithreading, whether the work is successful or not is uncertain. It needs to be executed cyclically and perform atomic operations through CAS.

1. CasNumberRange

2. Stack non-blocking algorithm: only the head pointer is saved and there is only one status

// Stack-implemented non-blocking algorithm: one-way linked list public class ConcurrentStack <E> {AtomicReference <Node <E> top = new AtomicReference <Node <E> (); public void push (E item) {Node <E> newHead = new Node <E> (item); Node <E> oldHead; do {oldHead = top. get (); newHead. next = oldHead;} while (! Top. compareAndSet (oldHead, newHead); // CAS operation: Atomic update operation, cyclic judgment, non-blocking} public E pop () {Node <E> oldHead; node <E> newHead; do {oldHead = top. get (); if (oldHead = null) {return null;} newHead = oldHead. next;} while (! Top. compareAndSet (oldHead, newHead); // CAS operation: Atomic update operation, cyclic judgment, non-blocking return oldHead. item;} private static class Node <E> {public final E item; public Node <E> next; public Node (E item) {this. item = item ;}}}

 

3. Non-Blocking Algorithms for linked lists: fast access to the header and tail stores two states, making it more complex.

Public class shortqueue <E> {private static class Node <E> {final E item; final AtomicReference <shortqueue. node <E> next; public Node (E item, queue. node <E> next) {this. item = item; this. next = new AtomicReference <queue. node <E >>( next) ;}} private final queue. node <E> dummy = new queue. node <E> (null, null); private final AtomicReference <LinkedQueue. node <E> head = new Atom IcReference <queue. node <E> (dummy); private final AtomicReference <queue. node <E> tail = new AtomicReference <queue. node <E> (dummy); // Save the public boolean put (E item) {incluqueue. node <E> newNode = new queue. node <E> (item, null); while (true) {queue. node <E> curTail = tail. get (); queue. node <E> tailNext = curTail. next. get (); if (curTail = tail. get () {if (tailNex T! = Null) {// It is in the intermediate state and the last node is updated to the next tail of the current last node. compareAndSet (curTail, tailNext);} else {// set the next of the current tail node to a new node: linked list if (curTail. next. compareAndSet (null, newNode) {/*** here is the intermediate state. Although two atomic operations are performed here, they are not atomic, but the algorithm ensures security: * The reason is that when other threads are in the intermediate state, the above if will be executed. * The above if operation is to help the current thread complete the last node update operation, but the current thread will fail to return the update, and eventually the update is successful * // the link is successful. If the tail node has changed, the current tail node is set to the new tail node. compareAndSet (curTail, newNode); return true ;}}}}}}

 

3. Atomic domain Updater

The above logic implements the non-blocking algorithm of the linked list, and uses Node to save the head knot and End Node

In the actual concurrent1_queue, the reflection-based AtomicReferenceFiledUpdater is used to encapsulate Node

V. ABA Problems

Common Problems in CAS operations:

If the value is A, the update operation is changed to B;

However, if A thread changes the value A to C and then changes it back to A, the original thread will judge that A = A successfully performs the update operation;

If you change A to C and then change it back to A, you also need to consider it as A change. You need to optimize the algorithm.

Solution: add the version number. Each update operation must update the version number, even if the value is the same.

      

 

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.