The secret of ThreadLocal

A threadLocal variable guareentes each thread has its own variable without worrying about synchronization. Usually a threadlocal variable is declared static to be initialized only once whenever threads access it. We can easily use Threadlocal in programm, but it is still worth to konw the detailed implemention of Threadlocal.

In ThreadLocal, ThreadLocalMap plays a key role. When invoking set() and get() method of ThreadLocal, actually these actions occur in ThreadLocalMap. ThreadLocalMap is naturally thread-local, bacause ThreadLocalMap is package private to allow declaration of fields in class Thread. A thread only has one ThreadLocalMap variable while associating with many ThreadLocal variables. The relationships among Thread, ThreadLocal, ThreadLocalMap are described as follows.

The picture above doesn't say the relationship between ThreadLocal and ThreadLocalMap, in order to describle the issue thoroughly, we would better to understand the structure of ThreadLocalMap. ThreadLocalMap mainly consists of a array of Entry, also called slots, Entry has two variables, one is called <ref> which is a ThreadLocal object as key, the other is value. So we illustrate the relationships in the following picture:

As shown in the picture above, one threadLocal object and a customized value is mapping to a entry in ThreadLocalMap. It is interesting that how to set or get a value quickly from ThreadLocalMap, for efficiency Java uses a magic number <0x61c88647>, this number is a near-optimally spread multiplicative hash value. For example:

        int HASH_CODE = 0;

        int HASH_INCREMENT = 0x61c88647; // magic number

        // generate numbers in 16
        int i=0;
        while(i < 16){
            HASH_CODE = HASH_CODE + HASH_INCREMENT;
            int index = HASH_CODE & (16 - 1);
            System.out.print(index + " ");
            i++;
        }

The result after execution is :

7 14 5 12 3 10 1 8 15 6 13 4 11 2 9 0

We can see that any two number are not same, so hashCode of threadLocal is set to that magic number, we can quickly get index of threadLocal in ThreadLocalMap like that. 

👉👉👉 自己搭建的租房网站:全网租房助手,m.kuairent.com,每天新增 500+房源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值