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!

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf


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

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!
