I was asked this question last week , I didn't think of it , It was later suggested that concurrent The atomic class in the bag . Come back and learn .

One 、 What is meant by Atomic？

Atomic The word has something to do with atoms , The latter was once thought to be the smallest unit of matter . In the computer Atomic Can't be divided into several parts . If a piece of code is considered Atomic, It means that this code is in the process of execution , It can't be interrupted . Generally speaking , Atomic instructions are provided by hardware , For software to implement atomic methods （ After a thread enters the method , Will not be interrupted , Until its execution is completed ）
  stay x86 On the platform ,CPU Provides the means to lock the bus during instruction execution .CPU There's a lead on the chip #HLOCK pin, If you prefix an instruction in an assembly language program "LOCK", The assembled machine code makes CPU In executing this command, put #HLOCK pin The potential of the current is lowered , Continue until the end of this command release , To lock the bus , So other things on the same bus CPU You can't access the memory through the bus for the time being , This ensures the atomicity of this instruction in a multiprocessor environment .
Two 、java.util.concurrent Atomic variables in

Whether direct or indirect , almost java.util.concurrent All classes in the package use atomic variables , Instead of using synchronization . similar ConcurrentLinkedQueue Class also uses atomic variables to directly implement the no wait algorithm , But similar ConcurrentHashMap Class using ReentrantLock Lock when needed . then , ReentrantLock Use atomic variables to maintain thread queues waiting to be locked .
without JDK 5.0 Medium JVM improvement , You will not be able to construct these classes , These improvements expose （ Add to class library , Not the user class ） Interface to access hardware level synchronization primitives . then ,java.util.concurrent Atomic variable classes and other classes in expose these functions to user classes
java.util.concurrent.atomic Atomic class of

This package provides a set of atomic classes . Its basic characteristic is in multithreading environment , When there are multiple threads executing the methods contained in the instances of these classes at the same time , Be exclusive , That is, when a thread enters a method , When executing the instructions , Will not be interrupted by other threads , And other threads are like spinlocks , Wait until the method execution is complete , Only by JVM Select another thread from the waiting queue to enter , It's just a logical understanding . In fact, it is realized by the related instructions of hardware , Will not block threads ( Or it's just blocking at the hardware level ). The classes can be divided into 4 Group
among AtomicBoolean,AtomicInteger,AtomicLong,AtomicReference It's similar .

First AtomicBoolean,AtomicInteger,AtomicLong,AtomicReference Inside api It's similar ： Take up a AtomicReference Example

Use AtomicReference Create a thread safe stack
Java Code

public class LinkedStack<T> {
private AtomicReference<Node<T>> stacks = new AtomicReference<Node<T>>();
public T push(T e) {
Node<T> oldNode, newNode;
while (true) { // The treatment here is very special , It has to be the same .
oldNode = stacks.get();
newNode = new Node<T>(e, oldNode);
if (stacks.compareAndSet(oldNode, newNode)) {
return e;
public T pop() {
Node<T> oldNode, newNode;
while (true) {
oldNode = stacks.get();
newNode = oldNode.next;
if (stacks.compareAndSet(oldNode, newNode)) {
return oldNode.object;
private static final class Node<T> {
private T object;
private Node<T> next;
this.object = object;
this.next = next;

Then focus on the atomic update of the field .

AtomicIntegerFieldUpdater<T>/AtomicLongFieldUpdater<T>/AtomicReferenceFieldUpdater<T,V> Is to update the value of a field based on reflection atoms .

Corresponding API It's also very simple , But there are also some constraints .

（1） Field must be volatile Type of ！volatile What is it . Please check out  
（2） The description type of the field （ Modifier public/protected/default/private） Is consistent with the relationship between the caller and the operation object field . That is to say, the caller can directly manipulate the object field , Then you can do atomic manipulation by reflection . But for fields of the parent class , Subclasses can't be manipulated directly , Although the subclass can access the fields of the parent class .

（3） Only instance variables , Can't be a class variable , That is to say, we can't add static keyword .

（4） Only modifiable variables , Can't make final Variable , because final The semantics of is immutable . actually final And volatile There is a conflict , These two keywords cannot exist at the same time .

（5） about AtomicIntegerFieldUpdater and AtomicLongFieldUpdater It can only be modified int/long Type field , You can't modify its packing type （Integer/Long）. If you want to change the packaging type, you need to use AtomicReferenceFieldUpdater.

The method of operation is described in the following example .

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
public class AtomicIntegerFieldUpdaterDemo {
class DemoData{
public volatile int value1 = 1;
volatile int value2 = 2;
protected volatile int value3 = 3;
private volatile int value4 = 4;
AtomicIntegerFieldUpdater<DemoData> getUpdater(String fieldName) {
return AtomicIntegerFieldUpdater.newUpdater(DemoData.class, fieldName);
void doit() {
DemoData data = new DemoData();
System.out.println("1 ==> "+getUpdater("value1").getAndSet(data, 10));
System.out.println("3 ==> "+getUpdater("value2").incrementAndGet(data));
System.out.println("2 ==> "+getUpdater("value3").decrementAndGet(data));
System.out.println("true ==> "+getUpdater("value4").compareAndSet(data, 4, 5));
public static void main(String[] args) {
AtomicIntegerFieldUpdaterDemo demo = new AtomicIntegerFieldUpdaterDemo();

In the example above DemoData Field of value3/value4 about AtomicIntegerFieldUpdaterDemo Class is invisible , Therefore, its value cannot be directly modified by reflection .

AtomicMarkableReference Class description <Object,Boolean> Right , It can be modified by atoms Object perhaps Boolean Value , This data structure is useful in some caching or state descriptions . This structure is modified individually or simultaneously Object/Boolean It can effectively improve throughput .

AtomicStampedReference Class maintenance with integers “ sign ” Object reference of , It can be updated atomically . contrast AtomicMarkableReference Class <Object,Boolean>,AtomicStampedReference Maintenance is similar to <Object,int> Data structure of , In fact, it is the right object （ quote ） A concurrent count of . But with the AtomicInteger The difference is , This data structure can carry an object reference （Object）, And can do atomic operations on this object and count at the same time .

At the end of this article we will mention “ABA problem ”, and AtomicMarkableReference/AtomicStampedReference Solving “ABA problem ” It's very useful .

3、 ... and 、Atomic The role of classes

Make the operation of single data , It's atomized
Use Atomic Class to build complex , Code that doesn't need to block
Access to 2 Or 2 More than one atomic Variable （ Or to a single atomic Variables to 2 Time or 2 More than one operation ） It's usually thought that synchronization is needed , So that these operations can be treated as an atomic unit .
No lock and no wait algorithm

be based on CAS （compare and swap） A parallel algorithm called No lock algorithm , Because threads don't have to wait for locking anymore （ Sometimes called mutually exclusive or critical parts , It depends on the terminology of the threading platform ）. No matter what CAS Operation success or failure , In either case , It's all done in a predictable time . If CAS Failure , The caller can try again CAS Operate or take other appropriate actions .
If each thread delays arbitrarily in other threads （ Or even fail ） Will continue to operate , It can be said that the algorithm is There is no waiting . In contrast to this , No lock algorithm requires only A thread always performs operations .（ Another definition of no wait is to ensure that each thread correctly calculates its own operation in its limited steps , Regardless of the operation of other threads 、 timing 、 Crossover or speed . This limitation can be System A function of the number of passes ; for example , If there is 10 Threads , Once per thread CasCounter.increment() operation , At worst , Each thread will have to retry up to nine times , To complete the increase .）
In the past 15 In the year , No wait and no lock algorithm has been studied （ Also known as Non blocking algorithm ） A lot of research has been done , Many people have found non blocking algorithms for common data structures . Non blocking algorithms are widely used in operating systems and JVM Level , Perform tasks such as thread and process scheduling . Although their implementation is complex , But compared to the alternative algorithm based on locking , They have many advantages ： It can avoid the danger of priority inversion and deadlock , Competition is cheaper , Coordination occurs at a finer level of granularity , Allow a higher degree of parallelism and so on .
common ：
Non blocking counter Counter
Non blocking stack ConcurrentStack
Non blocking list ConcurrentLinkedQueue

no need synchronized In the case of block, how to realize an atomic i++？ More articles about

  1. Use life examples to explain Java synchronized block

    Today's news of wechat apps all over the world , Everybody says that for Android Native programs are in danger , I don't want to , Who knows the future , I'd better carry out this year's plan .   The project just went online , Nothing's going on lately , I've always felt like my Java Basics ...

  2. Java Multithreading notes for basic knowledge enhancement 06：Lock Interface （ The difference in Synchronized block ）

    1. brief introduction We talked about how to use keywords synchronized To achieve synchronous access . In this paper, we will continue to explore this issue , from Java 5 after , stay java.util.concurrent.locks There's another way under the package ...

  3. Java Multithreading beginner's Guide （12）： Use Synchronized Block synchronization variables

    We can go through synchronized Block to synchronize specific static or non static methods . To implement this requirement, you must define a class variable for the method of these features , Then use the code of these methods to synchronized Put it all around , And pass this class variable as a parameter to ...

  4. Java Multithreading beginner's Guide （11）： Use Synchronized Block synchronization method

    synchronized There are two ways to use keywords . The first is in < Use Synchronized Keyword synchronization class method > This is directly used in the definition of methods . The other is synchronized block . We can not only ...

  5. Use Synchronized Block synchronization variables

    We can go through synchronized Block to synchronize specific static or non static methods . To implement this requirement, a class variable must be defined for these specific methods , Then use the code of these methods to synchronized Put it all around , And pass this class variable as a parameter to ...

  6. Use Synchronized Block synchronization method


  7. Synchronized The mistake of block synchronization variable


  8. synchronized In the block wait()、nofity()、nofityAll() Method

    Preface stay Java Concurrent programming practice , We often encounter multiple threads accessing the same resource , At this time, we need to maintain the consistency of the data , Otherwise, there will be various data errors , One way to synchronize is to use Synchronized Key execution lock mechanism , The locking mechanism is ...

  9. Properties in object Lock use ：volatile Keyword modification and no need synchronized Lock

    There is a state in an object attribute , Now the business needs There are multiple threads to modify and Take it to This state Value , In this case, how to add the lock ? One is stay set and get In this state Method Naga synchronized . And one more ...

Random recommendation

  1. LCS Record

    As the title : Find the longest common sequence of two sequences .( Such as :"ABCBDAB" And "BCDB" The longest common sequence is "BCDB") The code is as follows : #define MAX_SIZ ...

  2. javascript Core language notes 4 - Expressions and operators

    expression (expression) yes JavaScript A phrase in (phrases),JavaScript The interpreter will calculate (evaluate) Come up with a result . Constants in the program . Variable name . Array access and so on are expressions ...

  3. XML dynamic Insert The parent class indicates Subclass label

    Because of blogging for the first time , Where the writing is not good , Please give me more advice , Explain :xml Insert data dynamically and save , It took me a lot of effort to write this , Finally, the emperor finally let me do it , To share with you , Please point out the imperfections ...

  4. Abused for in loop

    as everyone knows ,javascript There are two kinds of for loop , One is : var a=['this','is','a','article'], i, len; for( i = 0,len = a.length;i ...

  5. Java Study —— for loop

    For Double cycle /* Loop statement nesting */ class ForForTest { public static void main(String[] args) { /*int x,y = 0; for( ...

  6. IOS Design pattern learning （7） Single case

    1 Preface In mathematics and logic ,singleton Defined as “ A collection of one and only one element ”. So no matter how big the bag is , Every time you take a bullet out of it , They all got the same . 2 detailed 2.1 sketch Singleton classes in object-oriented applications (si ...

  7. Swift introduction （ 5、 ... and ）—— Array （Array）

    aggregate Definition of set Swift Two kinds of data structures are provided in for storing data collection , Each is an array (Array) And the dictionary (Dictionary). The main difference is that the elements in the array are determined by subscripts . The value of the data in the dictionary is determined by the key of the data (K ...

  8. The etheric fang ERC20 Token development

    The etheric fang ERC20 Token development needs to focus on Ethereum first , Tokens, ,ERC20, Understanding the basic concepts in the development of Ethereum token, such as smart contract . According to our example code, we can issue our own Ethereum token . What is? ERC20 You can put ERC20 Simply understood as ether ...

  9. 【python】Django Custom template functions

    Reference resources :https://blog.csdn.net/wenyuanhai/article/details/73656761 Be careful : 1. The path of the custom template function must be APP Of templatetags Next :ap ...

  10. front end （HTML） initial

    One . use socket Realization HTML Principle import socket sk = socket.socket() sk.bind(('',8080)) sk.listen() while ...