Android 开发也要掌握的Java知识 -ThreadLocal

private static final int INITIAL_CAPACITY = 16;

/**

  • The table, resized as necessary.
  • table.length MUST always be a power of two.
    */
    private Entry[] table;

/**

  • The number of entries in the table.
    */
    private int size = 0;

/**

  • Construct a new map initially containing (firstKey, firstValue).
  • ThreadLocalMaps are constructed lazily, so we only create
  • one when we have at least one entry to put in it.
    */
    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
    }
    .
    .
    }
2.2.3 set(ThreadLocal<?> key, Object value)
  • 如果计算的位置已经有内容了,就覆盖,否则就新建一个Entry存放,再判断是否达到阈值,不够就扩容。

/**

  • Set the value associated with key.
  • @param key the thread local object
  • @param value the value to be set
    */
    private void set(ThreadLocal<?> key, Object value) {

// We don’t use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.

Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);

for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();

if (k == key) {
e.value = value;
return;
}

if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}

tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}

2.2.4 setInitialValue()
  • 初始化空Entry,因为有的线程ThreadLocal一开始没有存东西,但调用了get方法,这时候没内容,但还是先占个坑,返回null。

/**

  • Returns the current thread’s “initial value” for
  • 26
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值