Home  >  Article  >  Java  >  Example of Java implementing lock-free programming of cas instructions

Example of Java implementing lock-free programming of cas instructions

黄舟
黄舟Original
2017-09-15 11:07:211465browse

This article mainly introduces the lock-free programming implementation example of cas instruction in Java language. It has certain reference value and friends in need can learn about it.

The first time I came into contact with relevant content was with the volatile keyword. I know that it can ensure the visibility of variables, and it can be used to implement atomic operations of reading and writing. . . But to implement some compound operations volatile is powerless. . . The most typical representatives are increment and decrement operations. . . .

We know that in a concurrent environment, the simplest way to achieve data consistency is to lock, ensuring that only one thread can operate on the data at the same time. . . . For example, a counter can be implemented in the following way:


public class Counter {
  private volatile int a = 0;
  public synchronized int incrAndGet(int number) {
    this.a += number;
    return a;
  } 
  public synchronized int get() {
    return a;
  }
}

We modify all operations with the synchronized keyword to ensure synchronous access to attribute a. . . This can indeed ensure the consistency of a in a concurrent environment, but due to the use of locks, lock overhead, thread scheduling, etc., the scalability of the program is limited, so there are many lock-free implementations. . . .

In fact, these lock-free methods all use some CAS (compare and switch) instructions provided by the processor. What does this CAS do? You can use the following method to explain what CAS does. The semantics represented:


public synchronized int compareAndSwap(int expect, int newValue) {
    int old = this.a;
    if (old == expect) {
      this.a = newValue;
    }
    return old;
  }

Well, the CAS semantics should be very clear through the code. It seems that most processors now implement atomic CAS instructions. Come on. .
Okay, then let’s take a look at where CAS is used in Java. Let’s first look at the AtomicInteger type. This is a type provided in the concurrency library:


private volatile int value;

This is an internally defined attribute, used to save values. Since it is of volatile type, it can ensure the visibility between threads and the atomicity of reading and writing. . .
Then let’s take a look at some of the more commonly used methods:


public final int addAndGet(int delta) {
  for (;;) {
    int current = get();
    int next = current + delta;
    if (compareAndSet(current, next))
      return next;
  }
}

The function of this method is to add delta to the current value, you can see it here There is no lock in the entire method. This code is actually a method to implement a lock-free counter in Java. The compareAndSet method here is defined as follows:


public final boolean compareAndSet(int expect, int update) {
  return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

Due to calling unsafe method, so there is nothing you can do about it. In fact, you should be able to guess that the JVM calls the CAS instruction of the processor itself to implement atomic operations. . .

Basically, the important methods of the AtomicInteger type are implemented in a lock-free manner. . Therefore, in a concurrent environment, using this type can have better performance. . .
The above is considered to be a solution to implement lock-free counters in java. Next, let’s take a look at how to implement a lock-free stack and paste the code directly. The code is imitated from "JAVA Concurrent Programming Practice":


package concurrenttest;
import java.util.concurrent.atomic.AtomicReference;
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;
    while (true) {
      oldHead = top.get();
      newHead.next = oldHead;
      if (top.compareAndSet(oldHead, newHead)) {
        return;
      }
    }
  }
  public E pop() {
    while (true) {
      Node<e> oldHead = top.get();
      if (oldHead == null) {
        return null;
      }
      Node<e> newHead = oldHead.next;
      if (top.compareAndSet(oldHead, newHead)) {
        return oldHead.item;
      }
    }
  }
  private static class Node<e> {
    public final E item;
    public Node<e> next;
     
    public Node(E item) {
      this.item = item;
    }
  }
}

Okay, the above code implements a lock-free stack, simple. . . In a concurrent environment, lock-free data structures can scale much better than locks. . .
When talking about lock-free programming, we have to mention lock-free queues. In fact, the implementation of lock-free queues has been provided in the concurrent library: ConcurrentLinkedQueue. Let’s take a look at its important method implementation:


public boolean offer(E e) {
  checkNotNull(e);
  final Node<e> newNode = new Node<e>(e);
  for (Node<e> t = tail, p = t;;) {
    Node<e> q = p.next;
    if (q == null) {
      // p is last node
      if (p.casNext(null, newNode)) {
        // Successful CAS is the linearization point
        // for e to become an element of this queue,
        // and for newNode to become "live".
        if (p != t) // hop two nodes at a time
          casTail(t, newNode); // Failure is OK.
        return true;
      }
      // Lost CAS race to another thread; re-read next
    }
    else if (p == q)
      // We have fallen off list. If tail is unchanged, it
      // will also be off-list, in which case we need to
      // jump to head, from which all live nodes are always
      // reachable. Else the new tail is a better bet.
      p = (t != (t = tail)) ? t : head;
    else
      // Check for tail updates after two hops.
      p = (p != t && t != (t = tail)) ? t : q;
  }
}

This method is used to add elements to the end of the queue. Here you can see that there is no lock. For the specific lock-free algorithm, the non-locking algorithm proposed by Michael-Scott is used. Blocking linked list linking algorithm. . . To see how it works specifically, you can go to "JAVA Concurrent Programming in Practice" for a more detailed introduction.

In addition, other methods are actually implemented in a lock-free manner.

Finally, in actual programming, it is best to use these lock-free implementations in a concurrent environment, after all, it has better scalability.

Summarize

The above is the detailed content of Example of Java implementing lock-free programming of cas instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn