目录

JUC - 共享模型之无锁

笔记

前面都是介绍锁相关的知识,那么避免多线程安全问题,必须加锁吗?

当然不是,本内容介绍使用 CAS 的无锁机制,性能相比较加锁,更好一些。

2022-5-13 @YoungKbt

# 问题提出

有如下需求,保证 account.withdraw() 取款方法的线程安全:

interface Account {
    // 获取余额
    Integer getBalance();
    // 取款
    void withdraw(Integer amount);
    /**
     * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();
        
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        long end = System.nanoTime();
        System.out.println(account.getBalance() 
                           + " cost: " + (end-start) / 1000_000 + " ms");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

原有实现并不是线程安全的

class AccountUnsafe implements Account {
    private Integer balance;
    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }
    @Override
    public Integer getBalance() {
        return balance;
    }
    @Override
    public void withdraw(Integer amount) {
        balance -= amount;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

执行测试代码

public static void main(String[] args) {
    Account.demo(new AccountUnsafe(10000));
}
1
2
3

某次的执行结果

330 cost: 306 ms
1

# 为什么不安全

withdraw 方法是

public void withdraw(Integer amount) {
    balance -= amount;
}
1
2
3

对应的字节码

ALOAD 0 // <- this
ALOAD 0
GETFIELD cn/itcast/AccountUnsafe.balance : Ljava/lang/Integer; // <- this.balance
INVOKEVIRTUAL java/lang/Integer.intValue ()I // 拆箱
ALOAD 1 // <- amount
INVOKEVIRTUAL java/lang/Integer.intValue ()I // 拆箱
ISUB // 减法
INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer; // 结果装箱
PUTFIELD cn/itcast/AccountUnsafe.balance : Ljava/lang/Integer; // -> this.balance
1
2
3
4
5
6
7
8
9

多线程执行流程

ALOAD 0 // thread-0 <- this 
ALOAD 0 
GETFIELD cn/itcast/AccountUnsafe.balance // thread-0 <- this.balance 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
ALOAD 1 // thread-0 <- amount 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
ISUB // thread-0 减法
INVOKESTATIC java/lang/Integer.valueOf // thread-0 结果装箱
PUTFIELD cn/itcast/AccountUnsafe.balance // thread-0 -> this.balance 
 
ALOAD 0 // thread-1 <- this 
ALOAD 0 
GETFIELD cn/itcast/AccountUnsafe.balance // thread-1 <- this.balance 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
ALOAD 1 // thread-1 <- amount 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
ISUB // thread-1 减法
INVOKESTATIC java/lang/Integer.valueOf // thread-1 结果装箱
PUTFIELD cn/itcast/AccountUnsafe.balance // thread-1 -> this.balance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

看不懂字节码?来看文字总结

某情况下线程 t 执行 balance - amount = 330,但是没来得及将 330 赋值给 balance,其他线程一直往下执行到 balance = balance - amount = 0,最后线程 t 才能执行 balance = 330,所以最终结果不是 0,而是 330。

# 解决思路 - 加锁

首先想到的是给 Account 对象加 synchronized 锁

class AccountUnsafe implements Account {
    private Integer balance;
    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }
    @Override
    public synchronized Integer getBalance() {
        return balance;
    }
    @Override
    public synchronized void withdraw(Integer amount) {
        balance -= amount;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

结果是正确的,为

0 cost: 399 ms
1

# 解决思路 - 无锁

这里介绍 JDK 封装无锁的一个类:AtomicInteger,这个是 Integer 的原子类,即该类内部实现了线程安全问题,注意代码内部没有用到加锁机制,而是 CAS 机制

方法:

  • get():获取当前值
  • compareAndSet(int prev, int next):将 prev 与 get() 的值进行比较(可能 get() 的值被其他线程改了),相等则修改为 next,所以再次调用 get,就是 next 的值。如果修改失败,则返回 false,修改成功返回 true
  • addAndGet(int delta):先添加 delta 值,在 get 获取新增的值
class AccountSafe implements Account {
    private AtomicInteger balance;
    public AccountSafe(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }
    @Override
    public Integer getBalance() {
        return balance.get();
    }
    @Override
    public void withdraw(Integer amount) {
        while (true) {
            int prev = balance.get();
            int next = prev - amount;
            // 如果修改成功,则跳出循环,否则一直循环到修改成功为止
            if (balance.compareAndSet(prev, next)) {
                break;
            }
        }
        
        // 11 - 19 行代码可以简化为下面的方法
        // balance.addAndGet(-1 * amount);  // 等价于 balance.get() - (-1 * amount)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

执行测试代码

public static void main(String[] args) {
    Account.demo(new AccountSafe(10000));
}
1
2
3

某次的执行结果

0 cost: 302 ms
1

# CAS

前面看到的 AtomicInteger 的解决方法,内部并没有用锁来保护共享变量的线程安全。那么它是如何实现的呢?

public void withdraw(Integer amount) {
    while(true) {
        // 需要不断尝试,直到成功为止
        while (true) {
            // 比如拿到了旧值 1000
            int prev = balance.get();
            // 在这个基础上 1000-10 = 990
            int next = prev - amount;
            /*
             compareAndSet 正是做这个检查,在 set 前,先比较 prev 与当前值
             1. 不一致了,next 作废,返回 false 表示失败
             	比如,别的线程已经做了减法,当前值已经被减成了 990
             	那么本线程的这次 990 就作废了,进入 while 下次循环重试
             2. 一致,以 next 设置为新值,返回 true 表示成功
             */
            if (balance.compareAndSet(prev, next)) {
                break;
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

其中的关键是 compareAndSet,它的简称就是 CAS (也有 Compare And Swap 的说法),它必须是原子操作。

compareAndSet 翻译过来就是,先比较,再修改。它内部采用的是不断和当前值进行比较,如果相等则进行修改。为什么一直和当前值比较呢?因为当前值可能被其他线程修改。

如图,线程 1 拿到 100,然后减 10 得到 90,接着和当前值比较,如果仍然是 100,则说明没有被其他线程修改,直接将 100 改为 90,但是很不幸,线程 2 已经修改为 90,所以线程 1 重新获取 90,减 10 得到 80,再和当前值比较,发现是 90,所以直接改成 80,依此类推。

image-20220513215422009

注意:其实 CAS 的底层是 lock cmpxchg 指令(X86 架构),在单核 CPU 和多核 CPU 下都能够保证【比较-交换】的原子性

在多核状态下,某个核执行到带 lock 的指令时,CPU 会让总线锁住,当这个核把此指令执行完毕,再开启总线。这个过程中不会被线程的调度机制所打断,保证了多个线程对内存操作的准确性,是原子的。

# volatile

获取共享变量时,为了保证该变量的可见性,需要使用 volatile 修饰。

它可以用来修饰成员变量和静态成员变量,他可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作 volatile 变量都是直接操作主存。即一个线程对 volatile 变量的修改,对另一个线程可见。

注意:volatile 仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原子性)。

CAS 必须借助 volatile 才能读取到共享变量的最新值来实现「比较并交换」的效果,否则比较的时候,读取的是自己的缓存工作区,那么无论如何,缓存都是一个值。

请你谈谈你对 volatile 的理解

volitile 是 Java 虚拟机提供的轻量级的同步机制,三大特性:

  • 保证可见性

  • 不保证原子性

  • 禁止指令重排

# 为什么无锁效率高

无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized 会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。打个比喻:

  • 线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速等,恢复到高速运行,代价比较大
  • 但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换

# CAS 的特点

结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下

因为 CAS 不会发生阻塞,需要不断地运行,所以需要 CPU 的支持。如果线程数大于 CPU 数,那么就没有多余的 CPU 支持 CAS 运行,所以效率就不会那么明显,甚至效率比 synchronized 低。

  • CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,我吃亏点再重试呗
  • synchronized 是基于悲观锁的思想:最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会
  • CAS 体现的是无锁并发、无阻塞并发,请仔细体会这两句话的意思
    • 因为没有使用 synchronized,所以线程不会陷入阻塞,这是效率提升的因素之一
    • 但如果竞争激烈,可以想到重试必然频繁发生,反而效率会受影响

# 原子整数

JUC 并发包提供了三个原子性类:

  • AtomicInteger 原子整数
  • AtomicBoolean 原子布尔
  • AtomicLong 原子长整数

以 AtomicInteger 原子整数为例,介绍常用 API:

加减法 API:

public static void main(String[] args) {
    AtomicInteger i = new AtomicInteger(0);
    // 获取并自增(i = 0, 结果 i = 1, 返回 0),类似于 i++
    System.out.println(i.getAndIncrement());
    
    // 自增并获取(i = 1, 结果 i = 2, 返回 2),类似于 ++i
    System.out.println(i.incrementAndGet());
    
    // 自减并获取(i = 2, 结果 i = 1, 返回 1),类似于 --i
    System.out.println(i.decrementAndGet());
    
    // 获取并自减(i = 1, 结果 i = 0, 返回 1),类似于 i--
    System.out.println(i.getAndDecrement());
    
    // 获取并加值(i = 0, 结果 i = 5, 返回 0)
    System.out.println(i.getAndAdd(5));
    
    // 加值并获取(i = 5, 结果 i = 0, 返回 0)
    System.out.println(i.addAndGet(-5));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

如果想对值进行其他运算呢?如乘法、除法等。

public static void main(String[] args) {
    AtomicInteger i = new AtomicInteger(5);
    
    // 获取并更新(i = 5, v 为 i 的当前值, 结果 i = 10, 返回 5)
    // 其中函数中的操作能保证原子,但函数需要无副作用
    System.out.println(i.getAndUpdate(p -> p * 2));
    
    // 更新并获取(i = 10, p 为 i 的当前值, 结果 i = 20, 返回 20)
    System.out.println(i.updateAndGet(p -> p * 2));
    
    // 获取并计算(i = 20, p 为 i 的当前值, x 为参数 10, 结果 i = 200, 返回 20)
    // getAndUpdate 如果在 lambda 中引用了外部的局部变量,要保证该局部变量是 final 的
    // getAndAccumulate 可以通过参数 1 来引用外部的局部变量,但因为其不在 lambda 中因此不必是 final
    System.out.println(i.getAndAccumulate(10, (p, x) -> p * x));
    
    // 计算并获取(i = 200, p 为 i 的当前值, x 为参数 10, 结果 i = 20, 返回 20)
    System.out.println(i.accumulateAndGet(10, (p, x) -> p / x));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

当然上面 API 也能进行加法减法等任意运算。

说下这些封装好的 API 原理,其实内部使用了 compareAndSet() 方法 + while(true) 进行不断比较。

如自定义一个 updateAndGet() 方法:

public int updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
    while(true) {
        int prev = i.get();
        int next = operator.applyAsInt(prev);
        if(i.compareAndSet(prev, next)) {
            return next;
        }
    }
}
1
2
3
4
5
6
7
8
9

其中 IntUnaryOperator 是函数式接口,里面只有一个抽象方法 applyAsInt,它解决了 由用户决定进行加减乘除运算 的问题。

@FunctionalInterface
public interface IntUnaryOperator {
    int applyAsInt(int operand);
}
1
2
3
4

所以调用自定义的 updateAndGet() 方法:

public static void main(String[] args) {
    AtomicInteger i = new AtomicInteger(5);
    // operator.applyAsInt(prev) 的返回值等价于 p * 2,其中 prev = p
    System.out.println(i, updateAndGet(p -> p * 2)); // 输出 10
}
1
2
3
4
5

# 原子引用

为什么需要原子引用类型?

JDK 只提供的 AtomicInteger、AtomicBoolean、AtomicLong 三个具有针对性的原子性,那么 String、BigDecimal 这些引用类型呢?就需要原子引用类型了。

原子引用类型由三个:

  • AtomicReference 原子引用
  • AtomicMarkableReference 原子布尔引用
  • AtomicStampedReference 原子时间戳引用

# AtomicReference 使用

AtomicReference 利用泛型表示哪个引用类型,用法和 AtomicInteger 一样:

// 初始化值为 A
AtomicReference<String> ref = new AtomicReference<>("A");

// 获取值 A
String prev = ref.get();

// 将值修改为 B,如果成功,isSuccess 为 true,否则被人修改了,为 false
boolean isSuccess = ref.compareAndSet(prev, "B");
1
2
3
4
5
6
7
8

例子:

一个减去余额的类

public interface DecimalAccount {
    // 获取余额
    BigDecimal getBalance();
    // 取款
    void withdraw(BigDecimal amount);
    /**
     * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(DecimalAccount account) {
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(BigDecimal.TEN);
            }));
        }
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(account.getBalance());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

试着提供不同的 DecimalAccount 实现,实现安全的取款操作。

AtomicReference 的使用是第三种用法。

用法 1:不安全实现类

没有任何加锁或原子保护。

class DecimalAccountUnsafe implements DecimalAccount {
    BigDecimal balance;
    public DecimalAccountUnsafe(BigDecimal balance) {
        this.balance = balance;
    }
    @Override
    public BigDecimal getBalance() {
        return balance;
    }
    @Override
    public void withdraw(BigDecimal amount) {
        BigDecimal balance = this.getBalance();
        this.balance = balance.subtract(amount);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

用法 2:安全实现:使用锁

利用加锁解决线程安全问题。

class DecimalAccountSafeLock implements DecimalAccount {
    private final Object lock = new Object();
    BigDecimal balance;
    public DecimalAccountSafeLock(BigDecimal balance) {
        this.balance = balance;
    }
    @Override
    public BigDecimal getBalance() {
        return balance;
    }
    @Override
    public void withdraw(BigDecimal amount) {
        synchronized (lock) {
            BigDecimal balance = this.getBalance();
            this.balance = balance.subtract(amount);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

用法 3:安全实现:使用 CAS(AtomicReference)

利用 AtomicReference 解决线程安全问题,用法和 AtomicInteger 一样。

class DecimalAccountSafeCas implements DecimalAccount {
    AtomicReference<BigDecimal> ref;
    public DecimalAccountSafeCas(BigDecimal balance) {
        ref = new AtomicReference<>(balance);
    }
    @Override
    public BigDecimal getBalance() {
        return ref.get();
    }
    @Override
    public void withdraw(BigDecimal amount) {
        while (true) {
            BigDecimal prev = ref.get();
            BigDecimal next = prev.subtract(amount);
            if (ref.compareAndSet(prev, next)) {
                break;
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

测试代码

DecimalAccount.demo(new DecimalAccountUnsafe(new BigDecimal("10000")));
DecimalAccount.demo(new DecimalAccountSafeLock(new BigDecimal("10000")));
DecimalAccount.demo(new DecimalAccountSafeCas(new BigDecimal("10000")));
1
2
3

三种运行结果

4310 cost: 425 ms 
0 cost: 285 ms 
0 cost: 274 ms
1
2
3

# ABA 问题

ABA 问题指的是:线程 1 拿到的值 A,将值修改为 C 的之前,线程 2 拿到 A 并将 A 改成 B,然后线程 3 将 B 改成 A,此时线程 1 拿原来的 A 和修改后的 A 比较,发现确实是 A,所以改为 C。

虽然结果是对的,改成了 C,但是线程 1 并不知道,其实内部已经发生了更改。

public class Test {
    static AtomicReference<String> ref = new AtomicReference<>("A");
    public static void main(String[] args) throws InterruptedException {
        log.debug("main start...");
        // 获取值 A
        // 这个共享变量被它线程修改过?
        String prev = ref.get();

        other();

        sleep(1);
        // 尝试改为 C
        log.debug("change A->C {}", ref.compareAndSet(prev, "C"));
    }
    private static void other() {
        new Thread(() -> {
            log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
        }, "t1").start();
        sleep(0.5);
        new Thread(() -> {
            log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
        }, "t2").start();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

输出:

11:29:52.325 c.Test36 [main] - main start... 
11:29:52.379 c.Test36 [t1] - change A->B true 
11:29:52.879 c.Test36 [t2] - change B->A true 
11:29:53.880 c.Test36 [main] - change A->C true
1
2
3
4

主线程仅能判断出共享变量的值与最初值 A 是否相同,不能感知到这种从 A 改为 B 又改回 A 的情况。

# ABA 解决之 AtomicStampedReference

针对上面问题,如果主线程希望:只要有其它线程「动过了」共享变量,那么自己的 CAS 操作就算失败,这时,仅比较值是不够的,需要再加一个版本号。

版本号的原子引用类是 AtomicStampedReference,其中 Stamped 代表时间戳。

用法:

// 构造器的第一个参数是值,第二个参数是初始版本号
AtoAtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);

// 获取值 A
String prev = ref.getReference();

// 获取版本号 0
int stamp = ref.getStamp();

// 如果第三个参数与初始版本号一致,则将 A 改为 B,且将初始版本号 + 1
// 修改成功,isSuccess 为 true,否则为 false,代表当前 stamp 版本号和内部版本号不一样,被别人改了
boolean isSuccess = ref.compareAndSet(prev, "C", stamp, stamp + 1);

// 这里修改失败了,因为第三个参数与版本号不一致,版本号已经在上面(第 12 行)变成 1,而 stamp 依然是 0
boolean isSuccess = ref.compareAndSet(prev, "C", stamp, stamp + 1);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

优化例子:

public class Test {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
    public static void main(String[] args) throws InterruptedException {
        log.debug("main start...");
        // 获取值 A
        String prev = ref.getReference();
        // 获取版本号
        int stamp = ref.getStamp();
        log.debug("版本 {}", stamp);
        // 如果中间有其它线程干扰,发生了 ABA 现象
        other();
        sleep(1);
        // 尝试改为 C
        log.debug("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));
    }

    private static void other() {
        new Thread(() -> {
            log.debug("change A->B {}", ref.compareAndSet(ref.getReference(), "B", 
                                                          ref.getStamp(), ref.getStamp() + 1));
            log.debug("更新版本为 {}", ref.getStamp());
        }, "t1").start();
        sleep(0.5);
        new Thread(() -> {
            log.debug("change B->A {}", ref.compareAndSet(ref.getReference(), "A", 
                                                          ref.getStamp(), ref.getStamp() + 1));
            log.debug("更新版本为 {}", ref.getStamp());
        }, "t2").start();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

输出为:

15:41:34.891 c.Test36 [main] - main start... 
15:41:34.894 c.Test36 [main] - 版本 0 
15:41:34.956 c.Test36 [t1] - change A->B true 
15:41:34.956 c.Test36 [t1] - 更新版本为 1 
15:41:35.457 c.Test36 [t2] - change B->A true 
15:41:35.457 c.Test36 [t2] - 更新版本为 2 
15:41:36.457 c.Test36 [main] - change A->C false
1
2
3
4
5
6
7

AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如:A -> B -> A -> C,通过 AtomicStampedReference 我们可以知道,引用变量中途被更改了几次。

但是有时候,我们并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了 AtomicMarkableReference

# ABA 解决之 AtomicMarkableReference

AtomicMarkableReference 的 Markable 代表标记,它没有版本号,只有通过 true 和 false 判断数据是否被更改。

// 构造器的第一个参数是值,第二个参数是初始布尔值
AtomicMarkableReference<String> ref = new AtomicMarkableReference<>("A", true);

// 获取值 A
String prev = ref.getReference();

// 如果第三个参数与初始布尔值一致,则将 A 改为 B,且将初始布尔值改为 false:告诉别人我改了值
// 修改成功,isSuccess 为 true,否则为 false,代表别人修改初始布尔值为 false 了
boolean isSuccess = ref.compareAndSet(prev, "B", true, false);

// 这里修改失败了,因为第三个参数与布尔值不一致,布尔值已经在上面(第 9 行)改为 false
boolean isSuccess = ref.compareAndSet(prev, "B", true, false);
1
2
3
4
5
6
7
8
9
10
11
12

例子:

image-20220514011847939

垃圾袋类

class GarbageBag {
    String desc;
    public GarbageBag(String desc) {
        this.desc = desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    @Override
    public String toString() {
        return super.toString() + " " + desc;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

测试类

@Slf4j
public class TestABAAtomicMarkableReference {
    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag = new GarbageBag("装满了垃圾");
        // 参数2 mark 可以看作一个标记,表示垃圾袋满了
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);
        log.debug("主线程 start...");
        GarbageBag prev = ref.getReference();
        log.debug(prev.toString());
        
        new Thread(() -> {
            bag.setDesc("空垃圾袋");
            while (!ref.compareAndSet(bag, bag, true, false)) {}
            log.debug(bag.toString());
        }).start();
        
        Thread.sleep(1000);
        log.debug("主线程想换一只新垃圾袋?");
        boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
        log.debug("换了么?" + success);
        log.debug(ref.getReference().toString());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

输出:

2019-10-13 15:30:09.264 [main] 主线程 start... 
2019-10-13 15:30:09.270 [main] cn.itcast.GarbageBag@5f0fd5a0 装满了垃圾
2019-10-13 15:30:09.294 [Thread-1] cn.itcast.GarbageBag@5f0fd5a0 空垃圾袋
2019-10-13 15:30:10.294 [main] 主线程想换一只新垃圾袋?
2019-10-13 15:30:10.294 [main] 换了么?false 
2019-10-13 15:30:10.294 [main] cn.itcast.GarbageBag@5f0fd5a0 空垃圾袋
1
2
3
4
5
6

# 原子数组

上面的原子都是针对单个基本数据,那么数组的原子性类呢?

  • AtomicIntegerArray 原子整数数组
  • AtomicLongArray 原子长整数数组
  • AtomicReferenceArray 原子依赖数组

以 AtomicIntegerArray 原子整数数组为例:

// 初始化长度为 10 的数组,每个下标的元素都默认为 0
AtomicIntegerArray atomicArray = new AtomicIntegerArray(10);

for (int i = 0; i < length; i++) {
    // 每个线程对数组作 10000 次操作
    for (int index = 0; index < 10000; index++) {
        // 获取 idnex % atomicArray.length() 下标的值,进行 + 1
        atomicArray.getAndIncrement(index % atomicArray.length());
    }
}
// 输出:[10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
System.out.println(atomicArray);
1
2
3
4
5
6
7
8
9
10
11
12

提供一个通用性的例子:

/**
 参数1,提供数组、可以是线程不安全数组或线程安全数组
 参数2,获取数组长度的方法
 参数3,自增方法,回传 array, index
 参数4,打印数组的方法
*/
// supplier 提供者 无中生有 ()-> 结果
// function 函数 一个参数一个结果 (参数) -> 结果 , BiFunction (参数1,参数2) -> 结果
// consumer 消费者 一个参数没结果 (参数) -> void, BiConsumer (参数1,参数2) ->
private static <T> void demo(
    Supplier<T> arraySupplier,
    Function<T, Integer> lengthFun,
    BiConsumer<T, Integer> putConsumer,
    Consumer<T> printConsumer ) {
    List<Thread> ts = new ArrayList<>();
    T array = arraySupplier.get();
    int length = lengthFun.apply(array);
    for (int i = 0; i < length; i++) {
        // 每个线程对数组作 10000 次操作
        ts.add(new Thread(() -> {
            for (int j = 0; j < 10000; j++) {
                putConsumer.accept(array, j % length);
            }
        }));
    }
    ts.forEach(t -> t.start()); // 启动所有线程
    ts.forEach(t -> {
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }); // 等所有线程结束
    printConsumer.accept(array);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

实现 1:不安全的数组

demo(
    ()->new int[10],
    (array)->array.length,
    (array, index) -> array[index]++,
    array-> System.out.println(Arrays.toString(array))
);
1
2
3
4
5
6

结果:

[9870, 9862, 9774, 9697, 9683, 9678, 9679, 9668, 9680, 9698]
1

实现 2:安全的数组

demo(
    ()-> new AtomicIntegerArray(10),
    (array) -> array.length(),
    (array, index) -> array.getAndIncrement(index),
    array -> System.out.println(array)
);
1
2
3
4
5
6

结果

[10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
1

# 字段更新器

如果需要操作实体类里的属性,则需要 3 个字段更新器:

  • AtomicReferenceFieldUpdater 原子引用字段
  • AtomicIntegerFieldUpdater 原子整数字段
  • AtomicLongFieldUpdater 原子长整数字段

利用字段更新器,可以针对对象的某个域(Field)进行原子操作,只能配合 volatile 修饰的字段使用,否则会出现如下异常:

Exception in thread "main" java.lang.IllegalArgumentException: Must be volatile type
1

注意不是在实体类里操作某个属性,而是在外面拿出来后,再利用上面 3 个原子字段类进行封装。

例子 1:AtomicIntegerFieldUpdater

AtomicIntegerFieldUpdater 构造器两个参数:第一个是操作属性的 Class 类,第二个参数是操作的属性。

API 要带有属性所在的类对象。

public class Test5 {
    // 必须是 volatile
    private volatile int field;
    
    public static void main(String[] args) {
        AtomicIntegerFieldUpdater fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Test5.class, "field");
        Test5 test5 = new Test5();
        
        // API 要带有属性所在的类对象 test5。
        fieldUpdater.compareAndSet(test5, 0, 10);
        // 修改成功 field = 10
        System.out.println(test5.field);
        
        
        fieldUpdater.compareAndSet(test5, 10, 20);
        System.out.println(test5.field);
        
        // 修改失败 field = 20
        fieldUpdater.compareAndSet(test5, 10, 30);
        System.out.println(test5.field);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

输出:

10
20
20
1
2
3

例子 2:AtomicReferenceFieldUpdater

AtomicReferenceFieldUpdater 构造器三个参数:第一个是操作属性的 Class 类,第二个参数是操作属性的引用类型,第三个参数是操作的属性。

API 要带有属性所在的类对象。

public class Test5 {
    private volatile String field;
    
    public static void main(String[] args) {
        AtomicReferenceFieldUpdater fieldUpdater = AtomicReferenceFieldUpdater .newUpdater(TestPark.class, String.class, "field");
        Test5 test5 = new Test5();
        
        
        // API 要带有属性所在的类对象 test5。
        fieldUpdater.compareAndSet(test5, "", "hello");
        // 修改成功 field = hello
        System.out.println(test5.field);
        
        // 修改成功 field = world
        fieldUpdater.compareAndSet(test5, "hello", "world");
        System.out.println(test5.field);
        
        // 修改失败 field = 20
        fieldUpdater.compareAndSet(test5, "hello", "atomic");
        System.out.println(test5.field);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

输出:

hello
world
world
1
2
3

# 原子累加器

前面使用的 getAndIncrement 是一种累加方法,每个原子类都有这个方法,下面介绍一种专门用于累加的类:

  • DoubleAccumulator
  • DoubleAdder
  • LongAccumulator
  • LongAdder

Accumulator 和 Adder 区别

  • Adder 只针对数值的增减,Accumulator 针对自定义函数的增减

  • Adder 构造方法没有参数,Accumulator 有两个参数:

    • 参数 1:自定义运算
    • 参数 2:初始值
public class Striped64Thread extends Thread {
	// LongAdder 实例
	private LongAdder longAdder;
	// LongAccumulator 实例
	private LongAccumulator longAccumulator;
	// DoubleAdder 实例
	private DoubleAdder doubleAdder;
	// DoubleAccumulator 实例
	private DoubleAccumulator doubleAccumulator;

	public Striped64Thread(LongAdder longAdder, LongAccumulator longAccumulator, DoubleAdder doubleAdder,
			DoubleAccumulator doubleAccumulator) {
		this.longAdder = longAdder;
		this.longAccumulator = longAccumulator;
		this.doubleAdder = doubleAdder;
		this.doubleAccumulator = doubleAccumulator;
	}

	@Override
	public void run() {
		for (int index = 0; index < 10000; index++) {
			longAdder.increment();
			longAccumulator.accumulate(2);
			doubleAdder.add(2);
			doubleAccumulator.accumulate(3);
		}
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

测试类(看 Accumulator 和 Adder 的构造方法创建,就知道区别了):

public class Striped64Tester {
	// LongAdder 实例
	private static LongAdder longAdder = new LongAdder();
	// LongAccumulator 实例
	private static LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 100);
	// DoubleAdder 实例
	private static DoubleAdder doubleAdder = new DoubleAdder();
	// DoubleAccumulator 实例
	private static DoubleAccumulator doubleAccumulator = new DoubleAccumulator((x, y) -> x + y, 100);

	public static void main(String[] args) throws Exception {
		Striped64Thread striped64Thread1 = new Striped64Thread(longAdder, longAccumulator, doubleAdder, doubleAccumulator);
		Striped64Thread striped64Thread2 = new Striped64Thread(longAdder, longAccumulator, doubleAdder, doubleAccumulator);
		
		striped64Thread1.start();
		striped64Thread2.start();
		
		striped64Thread1.join();
		striped64Thread1.join();
		
		System.out.println("LongAdder:" + longAdder.sum());
		System.out.println("LongAccumulator:" + longAccumulator.get());
		System.out.println("DoubleAdder:" + doubleAdder.sum());
		System.out.println("DoubleAccumulator:" + doubleAccumulator.get());
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

输出结果(两个线程):

LongAdder20000
LongAccumulator40100
DoubleAdder40000.0
DoubleAccumulator60100.0
1
2
3
4

# 累加器性能比较

原子类自带的 getAndIncrement() 和原子累加器的 increment() 对比,明显原子累加器的 increment() 性能更好。

private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
    T adder = adderSupplier.get();
    long start = System.nanoTime();
    List<Thread> ts = new ArrayList<>();
    
    // 4 个线程,每人累加 50 万
    for (int i = 0; i < 40; i++) {
        ts.add(new Thread(() -> {
            for (int j = 0; j < 500000; j++) {
                action.accept(adder);
            }
        }));
    }
    ts.forEach(t -> t.start());
    
    ts.forEach(t -> {
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    long end = System.nanoTime();
    System.out.println(adder + " cost:" + (end - start)/1000_000);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

比较 AtomicLong 与 LongAdder:

for (int i = 0; i < 5; i++) {
    demo(() -> new LongAdder(), adder -> adder.increment());
}
for (int i = 0; i < 5; i++) {
    demo(() -> new AtomicLong(), adder -> adder.getAndIncrement());
}
1
2
3
4
5
6

输出

// increment 方法
1000000 cost:43 
1000000 cost:9 
1000000 cost:7 
1000000 cost:7 
1000000 cost:7
// getAndIncrement 方法
1000000 cost:31 
1000000 cost:27 
1000000 cost:28 
1000000 cost:24 
1000000 cost:22
1
2
3
4
5
6
7
8
9
10
11
12

性能提升的原因很简单,就是在有竞争时,设置多个累加单元,Therad-0 累加 Cell[0],而 Thread-1 累加 Cell[1],依此类推,最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。

# 源码之 LongAdder

视频:https://www.bilibili.com/video/BV16J411h7Rd?p=177

LongAdder 是并发大师 @author Doug Lea (大哥李)的作品,设计的非常精巧。

LongAdder 类有几个关键域:

// 累加单元数组, 懒惰初始化
transient volatile Cell[] cells;
// 基础值, 如果没有竞争, 则用 cas 累加这个域,否则使用 cells 数组进行累加
transient volatile long base;
// 在 cells 创建或扩容时, 置为 1, 表示加锁
transient volatile int cellsBusy;
1
2
3
4
5
6

CAS 锁

// 不要用于实践!这里只是演示
public class LockCas {
    private AtomicInteger state = new AtomicInteger(0);
    public void lock() {
        while (true) {
            // 如果原来的值不是 0,则一直 while 循环下去,否则就将 0 改为 1
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }
    public void unlock() {
        log.debug("unlock...");
        // 手动将值改为 0,避免 lock 方法一直处于 while 循环
        state.set(0);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

测试

public static void main(String[] args) {
    LockCas lock = new LockCas();
    
    new Thread(() -> {
        log.debug("begin...");
        lock.lock();
        try {
            log.debug("lock...");
            sleep(1);
        } finally {
            lock.unlock();
        }
    }).start();
    
    new Thread(() -> {
        log.debug("begin...");
        lock.lock();
        try {
            log.debug("lock...");
        } finally {
            lock.unlock();
        }
    }).start();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

输出:

18:27:07.198 c.Test42 [Thread-0] - begin... 
18:27:07.202 c.Test42 [Thread-0] - lock... 
18:27:07.198 c.Test42 [Thread-1] - begin... 
18:27:08.204 c.Test42 [Thread-0] - unlock... 
18:27:08.204 c.Test42 [Thread-1] - lock... 
18:27:08.204 c.Test42 [Thread-1] - unlock...
1
2
3
4
5
6

# 原理之伪共享

这段源码非常复杂,建议看视频学习,视频有 6 个:P178 - P183,这里提供 P178:https://www.bilibili.com/video/BV16J411h7Rd?p=178

其中 Cell 即为累加单元。

// 防止缓存行伪共享
@sun.misc.Contended
static final class Cell {
    volatile long value;
    Cell(long x) { value = x; }

    // 最重要的方法, 用来 cas 方式进行累加, prev 表示旧值, next 表示新值
    final boolean cas(long prev, long next) {
        return UNSAFE.compareAndSwapLong(this, valueOffset, prev, next);
    }
    // 省略不重要代码
}
1
2
3
4
5
6
7
8
9
10
11
12

注意 Cell 开头加了 Contended 注解,那么 Contended 是什么呢?得从缓存说起,缓存与内存的速度比较:

image-20220514220426055

从 cpu 到 大约需要的时钟周期
寄存器 1 cycle(4GHz 的 CPU 约为 0.25ns)
L1 缓存 3 ~ 4 cycle
L2 缓存 10 ~ 20 cycle
L3 缓存 40 ~ 45 cycle
内存 120 ~ 240 cycle

因为 CPU 与 内存的速度差异很大,需要靠预读数据至缓存来提升效率。

而缓存以缓存行为单位,每个缓存行对应着一块内存,一般是 64byte(8 个 long)。

缓存的加入会造成数据副本的产生,即 同一份数据会缓存在不同核心的同一缓存行中

CPU 要保证数据的一致性,如果某个 CPU 核心更改了数据,其它 CPU 核心对应的整个缓存行必须失效。

如下图,左侧的缓存数据与右侧的缓存数据在同一行,当左侧的 CPU Core 修改了缓存数据,那么右侧的缓存数据就会失效,所以右侧的 CPU Core 只能重新去内存获取,这浪费了效率。

image-20220514220729041

因为 Cell 是数组形式,在内存中是连续存储的,一个 Cell 为 24 字节(16 字节的对象头和 8 字节的 value),因此缓存行可以存下 2 个的 Cell 对象。这样问题来了:

  • Core-0 要修改 Cell[0]
  • Core-1 要修改 Cell[1]

无论谁修改成功,都会导致对方 Core 的缓存行失效,比如 Core-0 中 Cell[0] = 6000Cell[1] = 8000 要累加 Cell[0] = 6001Cell[1] = 8000 ,这时会让 Core-1 的缓存行失效。

@sun.misc.Contended 用来解决这个问题,它的原理是在使用此注解的对象或字段的前后各增加 128 字节大小的 padding,从而让 CPU 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效。

如下图,左侧的 CPU Core 修改了缓存数据,但是右侧的缓存数据处于另一行(加了 128 字节大小的 padding,导致换行),所以右侧的缓存数据不会失效,也就不会重新从内存读取数据。

image-20220514221336929

累加主要调用下面的方法:

public void add(long x) {
    // as 为累加单元数组
    // b 为基础值
    // x 为累加值
    Cell[] as; long b, v; int m; Cell a;
    // 进入 if 的两个条件
    // 1. as 有值, 表示已经发生过竞争, 进入 if
    // 2. cas 给 base 累加时失败了, 表示 base 发生了竞争, 进入 if
    if ((as = cells) != null || !casBase(b = base, b + x)) {
        // uncontended 表示 cell 没有竞争
        boolean uncontended = true;
        if (
            // as 还没有创建
            as == null || (m = as.length - 1) < 0 ||
            // 当前线程对应的 cell 还没有
            (a = as[getProbe() & m]) == null ||
            // cas 给当前线程的 cell 累加失败 uncontended=false ( a 为当前线程的 cell )
            !(uncontended = a.cas(v = a.value, v + x))
        ) {
            // 进入 cell 数组创建、cell 创建的流程
            longAccumulate(x, null, uncontended);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

add 流程图(边看图便阅读源码):

image-20220514221546082

final void longAccumulate(long x, LongBinaryOperator fn, boolean wasUncontended) {
    int h;
    // 当前线程还没有对应的 cell, 需要随机生成一个 h 值用来将当前线程绑定到 cell
    if ((h = getProbe()) == 0) {
        // 初始化 probe
        ThreadLocalRandom.current();
        // h 对应新的 probe 值, 用来对应 cell
        h = getProbe();
        wasUncontended = true;
    }
    // collide 为 true 表示需要扩容
    boolean collide = false; 
    for (;;) {
        Cell[] as; Cell a; int n; long v;
        // 已经有了 cells
        if ((as = cells) != null && (n = as.length) > 0) {
            // 还没有 cell
            if ((a = as[(n - 1) & h]) == null) {
                // 为 cellsBusy 加锁, 创建 cell, cell 的初始累加值为 x
                // 成功则 break, 否则继续 continue 循环
            }
            // 有竞争, 改变线程对应的 cell 来重试 cas
            else if (!wasUncontended)
                wasUncontended = true;
            // cas 尝试累加, fn 配合 LongAccumulator 不为 null, 配合 LongAdder 为 null
            else if (a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
                break;
            // 如果 cells 长度已经超过了最大长度, 或者已经扩容, 改变线程对应的 cell 来重试 cas
            else if (n >= NCPU || cells != as)
                collide = false;
            // 确保 collide 为 false 进入此分支, 就不会进入下面的 else if 进行扩容了
            else if (!collide)
                collide = true;
            // 加锁
            else if (cellsBusy == 0 && casCellsBusy()) {
                // 加锁成功, 扩容
                continue;
            }
            // 改变线程对应的 cell
            h = advanceProbe(h);
        }
        // 还没有 cells, 尝试给 cellsBusy 加锁
        else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
            // 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cell
            // 成功则 break;
        }
        // 上两种情况失败, 尝试给 base 累加
        else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
            break;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

longAccumulate 流程图(边看图便阅读源码):

image-20220514222407601

image-20220514232549067

每个线程刚进入 longAccumulate 时,会尝试对应一个 cell 对象(找到一个坑位)

image-20220514232621826

获取最终结果通过 sum 求和方法:

public long sum() {
    Cell[] as = cells; Cell a;
    long sum = base;
    if (as != null) {
        for (int i = 0; i < as.length; ++i) {
            if ((a = as[i]) != null)
                sum += a.value;
        }
    }
    return sum;
}
1
2
3
4
5
6
7
8
9
10
11

# Unsafe

# 概述

Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得。

# Unsafe CAS 操作

获取 Unsafe 的工具类

public class UnsafeAccessor {
    static Unsafe unsafe;
    static {
        try { 
            // Unsafe 类的 theUnsafe 变量是私有的,所以通过反射过去
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            // 允许使用 theUnsafe
            theUnsafe.setAccessible(true);
            // 获取真正的 Unsafe 对象
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new Error(e);
        }
    }
    static Unsafe getUnsafe() {
        return unsafe;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

学生类:

@Data
class Student {
    volatile int id;
    volatile String name;
}
1
2
3
4
5

测试类:

public static void main(String[] args) {
    Unsafe unsafe = UnsafeAccessor.getUnsafe();
    Field id = Student.class.getDeclaredField("id");
    Field name = Student.class.getDeclaredField("name");
    
    // 获得成员变量的偏移量
    long idOffset = unsafe.objectFieldOffset(id);
    long nameOffset = unsafe.objectFieldOffset(name);
    
    Student student = new Student();
    // 使用 cas 方法替换成员变量的值
    UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 true
    UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true
    System.out.println(student);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

输出:

Student(id=20, name=张三)
1

compareAndSwapIntcompareAndSwapObject 方法简写是 CAS,有四个参数:

  • 参数 1:操作属性所在的类对象,如操作 id,其所在的类对象是 student
  • 参数 2:操作属性的偏移量
  • 参数 3:当前属性的值
  • 参数 4:要修改的值

如果参数 3 的值与内部的值不一致(被别的线程修改),则修改失败,返回 false。,否则修改成参数 4 的值

# 自定义 AtomicData

使用自定义的 AtomicData 实现之前线程安全的原子整数 Account 实现。

自定义 AtomicData 类

class MyAtomicData {
    private volatile int data;
    static final Unsafe unsafe;
    static  long DATA_OFFSET;
    static {
        unsafe = UnsafeAccessor.getUnsafe();
        try {
            // data 属性在 DataContainer 对象中的偏移量,用于 Unsafe 直接访问该属性
            DATA_OFFSET = unsafe.objectFieldOffset(MyAtomicData.class.getDeclaredField("data"));
        } catch (NoSuchFieldException e) {
            throw new Error(e);
        }
    }
    public MyAtomicData(int data) {
        this.data = data;
    }
    public void decrease(int amount) {
        while(true) {
            // 获取共享变量旧值,可以在这一行加入断点,修改 data 调试来加深理解
            int prev = data;
            int next = prev - amount;
            // cas 尝试修改 data 为 旧值 + amount,如果期间旧值被别的线程改了,返回 false
            if (unsafe.compareAndSwapInt(this, DATA_OFFSET, prev, next)) {
                return;
            }
        }
    }
    public int getData() {
        return data;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Account 类

interface Account {
    // 获取余额
    Integer getBalance();
    // 取款
    void withdraw(Integer amount);
    /**
     * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();

        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }

        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long end = System.nanoTime();
        System.out.println(account.getBalance() 
                           + " cost: " + (end-start) / 1000_000 + " ms");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

测试

public class Test {
    public static void main(String[] args) {
        Account.demo(new Account() {
            MyAtomicData atomicData = new MyAtomicData(10000);
            @Override
            public Integer getBalance() {
                return atomicData.getData();
            }
            @Override
            public void withdraw(Integer amount) {
                atomicData.decrease(amount);
            }
        });
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

输出:

0 cost: 125ms
1
更新时间: 2024/01/17, 05:48:13
最近更新
01
JVM调优
12-10
02
jenkins
12-10
03
Arthas
12-10
更多文章>