java源码_ThreadLocal

每个Thread对象都有一个ThreadLocalMap对象,存储自己的ThreadLocal,存取ThreadLocal其实就是从ThreadLocalMap对象存取ThreadLocal

1.重要成员变量,hashCode的生成,其实就是AtomicInteger增加

private final int threadLocalHashCode = nextHashCode();//ThreadLocal的hash

/**
 * The next hash code to be given out. Updated atomically. Starts at
 * zero.
 */
private static AtomicInteger nextHashCode =
    new AtomicInteger();

/**
 * The difference between successively generated hash codes - turns
 * implicit sequential thread-local IDs into near-optimally spread
 * multiplicative hash values for power-of-two-sized tables.
 */
private static final int HASH_INCREMENT = 0x61c88647;

/**
 * Returns the next hash code.
 */
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}

2.set

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);//获得map
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}
3.get方法
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);//获得map
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);//从map里获得Entry
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

4.remove

public void remove() {
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}

发布了138 篇原创文章 · 获赞 10 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/idealemail/article/details/80437367