Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use lock-free technology in Java

Shulou Source: shulou.com Published: 2022-06-02 19:58:15 09月30日 Update

This article introduces the knowledge of "how to use lock-free technology in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Atomic tool class

In JDK 1.8, the classes under the java.util.concurrent.atomic package are all atomic classes, and atomic classes are all implemented based on sun.misc.Unsafe.

In order to solve the concurrency problem, CPU provides CAS instruction, full name Compare And Swap, that is, compare and interact.

The CAS instruction requires three parameters, variables, comparison values, and new values. Update the variable to the new value only when the current value of the variable is equal to the comparison value

CAS is a CPU instruction that is guaranteed atomicity at the CPU hardware level

The atoms in the java.util.concurrent.atomic package are divided into: atomic basic data type, atomic object reference type, atomic array, atomic object attribute updater and atomic accumulator.

Atomic basic data types: AtomicBoolean, AtomicInteger, AtomicLong

Atomic object reference types: AtomicReference, AtomicStampedReference, AtomicMarkableReference

Atomic arrays: AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray

Atomic object property updates: AtomicIntegerFieldUpdater, AtomicLongFieldUpdater, AtomicReferenceFieldUpdater

Atomic accumulator: DoubleAccumulator, DoubleAdder, LongAccumulator, LongAdder

Modify the class that we tested for atomicity problems earlier, using a simple example of AtomicInteger

Package constxiong.concurrency.a026; import java.util.concurrent.atomic.AtomicInteger; / * Test atomic class AtomicInteger * * @ author ConstXiong * / public class TestAtomicInteger {/ / count variable static volatile AtomicInteger count = new AtomicInteger (0); public static void main (String [] args) throws InterruptedException {/ / Thread 1 adds 10000 Thread T1 = new Thread (())-> {for (int j = 0; j {for (int j = 0; j)

Tags: Atoms threads variables storage problems objects data types tests that is instructions arrays integers results updates techniques examples memory content properties Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Microsoft macOS MySQL