
在 FutureTask 里面,普通写和 CAS 写是 混合使用的。比如
public boolean cancel(boolean mayInterruptIfRunning) { if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) return false; try { // in case call to interrupt throws exception if (mayInterruptIfRunning) { try { Thread t = runner; if (t != null) t.interrupt(); } finally { // final state UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); //这里是普通写语义 } } } finally { finishCompletion(); } return true; } 我这么解释对吗:
1 BBCCBB 2020 年 8 月 17 日 手里的 jdk11 实现已经不是这个 putOrderedInt 了. 不过我感觉套路都差不多, 就是要么是在加锁里面执行的, 要么是有 volatile 字段更新, 捎带就把他的缓存给清了. |
2 BBCCBB 2020 年 8 月 17 日 |
3 amiwrong123 OP @BBCCBB volatile变量的修改可以立刻让所有的线程可见,这个确实很好理解,对于同一个字段来说。 但其实,对 A 字段的 CAS 写操作,可以让其他所有字段的普通写操作,也马上可见。我这么理解对不 |
4 BBCCBB 2020 年 8 月 17 日 |