Example of Java implementing lock-free programming of cas instructions
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
