atomic

AbstractQueuedSynchronizer implementation principle - 2

Preface In the previous articleAbstractQueuedSynchronizer implementation principle - 1, we explained the acquisition and release of exclusive synchronization state in AbstractQueuedSynchronizer, and here we start to explain the acquisition and release of shared synchronization state in AbstractQueuedSynchronizer. Shared Synchronous State Acquisition and Release Shared lock as the name implies is that multiple threads can share a lock, use acquireShared in the synchronizer to get the shared lock (synchronous state), the source code of the method is as follows.

AbstractQueuedSynchronizer implementation principle - 1

Preface AbstractQueuedSynchronizer is the basic framework for implementing concurrency tools in the JDK, and a deeper understanding of it will help us to better use its features and related tools. We hope you will read this article carefully and gain something from it. In Java, access to shared resources by multiple threads is controlled by lock. We know that the lock function can be implemented by the synchronized keyword, which can implicitly acquire locks, that is, we do not need to care about the process of acquiring and releasing locks by using this keyword, but while it provides convenience, it also means that its flexibility is reduced.

Simple use of the Atomic class

Problem Background In a multi-threaded environment, the most common problem we encounter is synchronizing the values of variables. Since variables need to be shared across multiple threads, we must need to employ some synchronization mechanism to control them. From the previous article we know that the Lock mechanism can be used, and of course, the Atomic class we are talking about today. Here we will introduce each of the two ways.

Principle of implementation of atomic operations

1. Introduction Atomic means “the smallest particle that cannot be further divided”, and atomic operation means “an operation or series of operations that cannot be interrupted”. Implementing atomic operations on a multiprocessor becomes a bit complicated. In this article, let’s talk about how atomic operations are implemented on Intel processors and in Java. 2. Definition of Terms Compare and Swap CAS operations require two values to be entered, an old value (the value before the desired operation) and a new value, during which the old value is compared to the new value if it has not changed, and not exchanged if it.