MtContextThreadLocal(一)

来源:互联网 发布:家庭装修网络布线图 编辑:程序博客网 时间:2024/05/16 06:25

AtomicReference干嘛的?
假设releaseMtContextAfterRun为true,那么上下文仅能被执行线程使用一次。
所以

@Overridepublic void run() {    Map<MtContextThreadLocal<?>, Object> copied = copiedRef.get();    if (copied == null || releaseMtContextAfterRun && !copiedRef.compareAndSet(copied, null)) {        throw new IllegalStateException("MtContext is released!");    }    //recover context may be more easy to understand.    Map<MtContextThreadLocal<?>, Object> backup = MtContextThreadLocal.backupAndSet(copied);    try {        runnable.run();    } finally {       MtContextThreadLocal.restore(backup);    }}

只有设置了releaseMtContextAfterRun为true,那么多个线程读取时才会使用CAS获取竞态资源。
if(copied==null||(releaseMtContextAfterRun &&copiedRef.compareAndSwap(copyied,null))){
}

In fact.ThreadLocal的内部类ThreadLocalMap是个WeakHashMap

0 0