Concurrent programming (6): Atomic atoms (interview detailed)

One: what is the atom class

 

 Atomic means that an operation is uninterruptible, even when multiple threads are executed together, once an operation starts, it will not be interfered by other threads.

basic type

Update basic types using atomic methods

  • AtomicInteger: shaping atom class
  • AtomicLong: Long atom type
  • AtomicBoolean: Boolean atom class

Array type

Update an element in an array using atomic methods

  • AtomicIntegerArray: integer array atomic class
  • AtomicLongArray: Long integer array atom class
  • AtomicReferenceArray: Reference type array atomic class

Reference type

  • AtomicReference: Reference type atomic class
  • AtomicStampedReference: Atomic update field type in the reference type
  • AtomicMarkableReference: atomic update reference type with mark bit

Object property modification type

  • AtomicIntegerFieldUpdater: Atomic updater updater
  • AtomicLongFieldUpdater: updater for atomically updating long integer fields
  • AtomicStampedReference: Atomic update reference type with version number. This class associates integer values ​​with references and can be used to solve atomic update data and data version numbers. It can solve ABA problems that may occur when using CAS to perform atomic updates.

 

Two: common methods

Take AtomicInteger as an example

public final int get() //获取当前的值
public final int getAndSet(int newValue)//获取当前的值,并设置新的值
public final int getAndIncrement()//获取当前的值,并自增
public final int getAndDecrement() //获取当前的值,并自减
public final int getAndAdd(int delta) //获取当前的值,并加上预期的值
boolean compareAndSet(int expect, int update) //如果输入的数值等于预期值,则以原子方式将该值设置为输入值(update)
public final void lazySet(int newValue)//最终设置为newValue,使用 lazySet 设置之后可能导致其他线程在之后的一小段时间内还是可以读到旧的值。

Three: The principle of AtomicInteger class

 

Source code:

private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
    try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicInteger.class.getDeclaredField("value"));
    } catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;

Mainly use CAS (compare and swap) + volatile and native methods to ensure atomic operations.

For details, please refer to the article on Understanding the CAS Mechanism.

 

Finally, in accordance with established practice, the wife townhouse.


 

Published 28 original articles · praised 0 · visits 9931

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/105591201