MtContextThreadLocal(一)

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

@Override
public void run() {
    Map, 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, 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

你可能感兴趣的:(java,java,线程)