ThreadLocal source code analysis – java8

1. Characteristic analysis

Threadlocalhashcode describes a custom hash value (valid only in threadlocalmaps), which eliminates the conflict of using continuously constructed threadlocals by the same thread in common cases, and can maintain good performance in less common cases. The initialization value is null. If the programmer expects the local variable to have an initial value instead of null, ThreadLocal must be subclassed and the initialvalue () method is overridden. Public t get() function: returns the value of the current thread's copy of this local variable. If the current thread does not have the value of this variable, it will first be initialized to the value called by the initialvalue method, which is null by default. Method executes the process public void set (t value) function: set the copy of the local variable of the current thread to the specified value. Most subclasses do not need to override this method, but only rely on the initialvalue() method to assign a value to the local variable of the thread. Method execution process threadlocalmap class static class threadlocalmap is a custom hash map, which is only applicable to maintaining thread local values. No operations were exported to the ThreadLocal class This class is private at the package level and allows the variable entry declared in the thread class to define key: ThreadLocal value: the value corresponding to ThreadLocal refers to the key of weak reference type in the entry of hash table. Purpose: to assist in handling large and long-life use. Because the reference queue is not used, the old entries are deleted only when the entry runs out of table memory space The key of null value means that this key is no longer referenced, which means that this entry can be deleted from the table Such entries are called "obsolete entries". Initialize a table with a capacity of 16 that can be expanded. Double the expansion load factor: 2 / 3 delete the old entry, It solves the memory overflow problem caused by weak references. The method involved private entry getentry (ThreadLocal key) deletes multiple old entries private void set (ThreadLocal key, object value) and deletes one or more old entries private Boolean cleansomeslots (int i, int n) private void rehash()

package sourcecode. analysis;

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>