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+房源