背景
在sentinel底层中的滑动窗口,使用了AtomicReferenceArray来包裹 array
组件作为底层存在,可能对话在限流的时候,
- 1.并发高
- 2.存在race condition
- 3.延迟低
存在race condition的时候,我们习惯意义上会去想通过锁,但是随着线程多,会导致上下文切换,延时是不可接受
解决方案
使用AtomicReferenceArray
public static void main(String[] args) {AtomicReferenceArray<String> array = new AtomicReferenceArray<>(10);for(int i = 0;i<10;i++){int finalI = i;Thread t = new Thread(()->{try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}boolean b = array.compareAndSet(1, null, "Thread index" + finalI);if (!b){System.out.println("current thread cas error"+finalI);}});t.start();}try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(array.get(1));}
这个array 通过cas方式,解决并发情况下的竞争
