本文共 18698 字,大约阅读时间需要 62 分钟。
举例:
package top.nnzi.concurrent.chapter02;import java.util.ArrayList;import java.util.List;import java.util.concurrent.atomic.AtomicInteger;/** * @Description: 无锁解决线程安全问题 * @Author: Aiguodala * @CreateDate: 2021/4/9 22:55 */public class CASTest { public static void main(String[] args) { Account.demo(new AccountUnsafe(10000)); Account.demo(new AccountCas(10000)); }}interface Account { Integer getBalance(); void withdraw(Integer amount); /** * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作 * 如果初始余额为 10000 那么正确的结果应当是 0 */ static void demo(Account account) { Listts = 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"); }}//线程不安全的做法class AccountUnsafe implements Account { private Integer balance; public AccountUnsafe(Integer balance) { this.balance = balance; } @Override public Integer getBalance() { return this.balance; } @Override public synchronized void withdraw(Integer amount) { balance -= amount; }}//线程安全的做法class AccountCas implements Account { //使用原子整数 private AtomicInteger balance; public AccountCas(int 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; } } }}
前面看到的 AtomicInteger 的解决方法,内部并没有用锁来保护共享变量的线程安全。那么它是如何实现的呢?
其中的关键是 compareAndSwap(比较并设置值),它的简称就是 CAS (也有 Compare And Swap 的说法),它必须是原子操作。
注意
其实 CAS 的底层是 lock cmpxchg 指令(X86 架构),在单核 CPU 和多核 CPU 下都能够保证【比较-交换】的原子性。
在多核状态下,某个核执行到带 lock 的指令时,CPU 会让总线锁住,当这个核把此指令执行完毕,再开启总线。这个过程中不会被线程的调度机制所打断,保证了多个线程对内存操作的准确性,是原子的。
volatile
注意
CAS特点
结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。
J.U.C 并发包提供了
package top.nnzi.concurrent.chapter02;import java.util.concurrent.atomic.AtomicInteger;/** * @Description: * @Author: Aiguodala * @CreateDate: 2021/4/9 23:29 */public class AtomicTest { 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)); // 获取并更新(i = 0, p 为 i 的当前值, 结果 i = -2, 返回 0) // 其中函数中的操作能保证原子,但函数需要无副作用 System.out.println(i.getAndUpdate(p -> p - 2)); // 更新并获取(i = -2, p 为 i 的当前值, 结果 i = 0, 返回 0) // 其中函数中的操作能保证原子,但函数需要无副作用 System.out.println(i.updateAndGet(p -> p + 2)); // 获取并计算(i = 0, p 为 i 的当前值, x 为参数1, 结果 i = 10, 返回 0) // 其中函数中的操作能保证原子,但函数需要无副作用 // getAndUpdate 如果在 lambda 中引用了外部的局部变量,要保证该局部变量是 final 的 // getAndAccumulate 可以通过 参数1 来引用外部的局部变量,但因为其不在 lambda 中因此不必是 final int a = 0; System.out.println(i.getAndAccumulate(a, (p, x) -> p + x)); // 计算并获取(i = 10, p 为 i 的当前值, x 为参数1, 结果 i = 0, 返回 0) // 其中函数中的操作能保证原子,但函数需要无副作用 System.out.println(i.accumulateAndGet(-10, (p, x) -> p + x)); }}
用于解决需要进行原子操作的数据不是基本类型
public interface DecimalAccount { BigDecimal getBalance(); void withdraw(BigDecimal amount); /** * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作 * 如果初始余额为 10000 那么正确的结果应当是 0 */ static void demo(DecimalAccountImpl account) { Listts = new ArrayList<>(); long start = System.nanoTime(); 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(); } }); long end = System.nanoTime(); System.out.println(account.getBalance() + " cost: " + (end - start) / 1000_000 + " ms"); }}class DecimalAccountImpl implements DecimalAccount { //原子引用,泛型类型为小数类型 AtomicReference balance; public DecimalAccountImpl(BigDecimal balance) { this.balance = new AtomicReference (balance); } @Override public BigDecimal getBalance() { return balance.get(); } @Override public void withdraw(BigDecimal amount) { while(true) { BigDecimal pre = balance.get(); BigDecimal next = pre.subtract(amount); if(balance.compareAndSet(pre, next)) { break; } } } public static void main(String[] args) { DecimalAccount.demo(new DecimalAccountImpl(new BigDecimal("10000"))); }}
public class Demo3 { static AtomicReferencestr = new AtomicReference<>("A"); public static void main(String[] args) { new Thread(() -> { String pre = str.get(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //把str中的A改为C System.out.println("change A->C " + str.compareAndSet(pre, "C")); }).start(); } static void other() throws InterruptedException { new Thread(()-> { System.out.println("change A->B " + str.compareAndSet("A", "B")); }).start(); Thread.sleep(500); new Thread(()-> { System.out.println("change B->A " + str.compareAndSet("B", "A")); }).start(); }}
主线程仅能判断出共享变量的值与初值 A 是否相同,不能感知到这种从 A 改为 B 又 改回 A 的情况,如果主线程希望:只要有其它线程【动过了】共享变量,那么自己的 cas 就算失败,这时,仅比较值是不够的,需要再加一个版本号
AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如: A -> B -> A -> C ,通过AtomicStampedReference,我们可以知道,引用变量中途被更改了几次。
public class Demo3 { //指定版本号 static AtomicStampedReferencestr = new AtomicStampedReference<>("A", 0); public static void main(String[] args) { new Thread(() -> { String pre = str.getReference(); //获得版本号 int stamp = str.getStamp(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //把str中的A改为C,并比对版本号,如果版本号相同,就执行替换,并让版本号+1 System.out.println("change A->C stamp " + stamp + str.compareAndSet(pre, "C", stamp, stamp+1)); }).start(); } static void other() throws InterruptedException { new Thread(()-> { int stamp = str.getStamp(); System.out.println("change A->B stamp " + stamp + str.compareAndSet("A", "B", stamp, stamp+1)); }).start(); Thread.sleep(500); new Thread(()-> { int stamp = str.getStamp(); System.out.println("change B->A stamp " + stamp + str.compareAndSet("B", "A", stamp, stamp+1)); }).start(); }}
但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了 AtomicMarkableReference
public class Demo4 { //指定版本号 static AtomicMarkableReferencestr = new AtomicMarkableReference<>("A", true); public static void main(String[] args) { new Thread(() -> { String pre = str.getReference(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //把str中的A改为C,并比对版本号,如果版本号相同,就执行替换,并让版本号+1 System.out.println("change A->C mark " + str.compareAndSet(pre, "C", true, false)); }).start(); } static void other() throws InterruptedException { new Thread(() -> { System.out.println("change A->A mark " + str.compareAndSet("A", "A", true, false)); }).start(); }}
两者的区别
AtomicStampedReference 需要我们传入整型变量作为版本号,来判定是否被更改过
AtomicMarkableReference需要我们传入布尔变量作为标记,来判断是否被更改过
public class Demo1 { public static void main(String[] args) { Student student = new Student(); // 获得原子更新器 // 泛型 // 参数1 持有属性的类 参数2 被更新的属性的类 // newUpdater中的参数:第三个为属性的名称 AtomicReferenceFieldUpdaterupdater = AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name"); // 修改 updater.compareAndSet(student, null, "lby"); System.out.println(student); }}class Student { volatile String name; @Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; }}
LongAdder 是原子累加器,提供了更快的性能。
/** * Table of cells. When non-null, size is a power of 2. */ transient volatile Cell[] cells; /** * Base value, used mainly when there is no contention, but also as * a fallback during table initialization races. Updated via CAS. */ transient volatile long base; /** * Spinlock (locked via CAS) used when resizing and/or creating Cells. */ transient volatile int cellsBusy;
无论谁修改成功,都会导致对方 Core 的缓存行失效,
比如 Core-0 中 Cell[0]=6000, Cell[1]=8000 要累加 Cell[0]=6001, Cell[1]=8000 ,这时会让 Core-1 的缓存行失效
@sun.misc.Contended 用来解决这个问题,它的原理是在使用此注解的对象或字段的前后各增加 128 字节大小的 padding(空白),从而让 CPU 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效
@sun.misc.Contended static final class Cell { volatile long value; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long valueOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class ak = Cell.class; valueOffset = UNSAFE.objectFieldOffset (ak.getDeclaredField("value")); } catch (Exception e) { throw new Error(e); } } }
public void add(long x) { Cell[] as; long b, v; int m; Cell a; if ((as = cells) != null || !casBase(b = base, b + x)) { boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[getProbe() & m]) == null || !(uncontended = a.cas(v = a.value, v + x))) longAccumulate(x, null, uncontended); } }
final void longAccumulate(long x, LongBinaryOperator fn, boolean wasUncontended) { int h; if ((h = getProbe()) == 0) { ThreadLocalRandom.current(); // force initialization h = getProbe(); wasUncontended = true; } boolean collide = false; // True if last slot nonempty for (;;) { Cell[] as; Cell a; int n; long v; if ((as = cells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (cellsBusy == 0) { // Try to attach new Cell Cell r = new Cell(x); // Optimistically create if (cellsBusy == 0 && casCellsBusy()) { boolean created = false; try { // Recheck under lock Cell[] rs; int m, j; if ((rs = cells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { cellsBusy = 0; } if (created) break; continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail wasUncontended = true; // Continue after rehash else if (a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x)))) break; else if (n >= NCPU || cells != as) collide = false; // At max size or stale else if (!collide) collide = true; else if (cellsBusy == 0 && casCellsBusy()) { try { if (cells == as) { // Expand table unless stale Cell[] rs = new Cell[n << 1]; for (int i = 0; i < n; ++i) rs[i] = as[i]; cells = rs; } } finally { cellsBusy = 0; } collide = false; continue; // Retry with expanded table } h = advanceProbe(h); } else if (cellsBusy == 0 && cells == as && casCellsBusy()) { boolean init = false; try { // Initialize table if (cells == as) { Cell[] rs = new Cell[2]; rs[h & 1] = new Cell(x); cells = rs; init = true; } } finally { cellsBusy = 0; } if (init) break; } else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x)))) break; // Fall back on using base } }
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; }
Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得
import sun.misc.Unsafe;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;/** * @Description: * @Author: Aiguodala * @CreateDate: 2021/4/10 14:54 */public class GetUnsafe { public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { // 通过反射获得Unsafe对象 Class unsafeClass = Unsafe.class; // 获得构造函数,Unsafe的构造函数为私有的 Constructor constructor = unsafeClass.getDeclaredConstructor(); // 设置为允许访问私有内容 constructor.setAccessible(true); // 创建Unsafe对象 Unsafe unsafe = (Unsafe) constructor.newInstance(); // 创建Person对象 Person person = new Person(); // 获得其属性 name 的偏移量 Field field = Person.class.getDeclaredField("name"); long offset = unsafe.objectFieldOffset(field); // 通过unsafe的CAS操作改变值 unsafe.compareAndSwapObject(person, offset, null, "AIguodala"); System.out.println(person); }}class Person { // 配合CAS操作,必须用volatile修饰 volatile String name; @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; }}
package objectShare;import sun.misc.Unsafe;import java.lang.reflect.Constructor;/** * @Description: * @Author: Aiguodala * @CreateDate: 2021/4/10 16:02 */public class MyAtomicInteger { private volatile int value; private static final long valueOffset; private static final Unsafe UNSAFE; static { Class unsafeClass = Unsafe.class; try { Constructor constructor = unsafeClass.getDeclaredConstructor(); constructor.setAccessible(true); UNSAFE = (Unsafe) constructor.newInstance(); valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value")); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } public int getValue() { return value; } public void decrement(int x) { while (true) { int pre = getValue(); int next = pre - x; if (UNSAFE.compareAndSwapInt(this,value,pre,next)) { break; } } }}
转载地址:http://ssfz.baihongyu.com/