ThreadLocal Thread Local variable and source code analysis, threadlocal source code

Source: Internet
Author: User

ThreadLocal Thread Local variable and source code analysis, threadlocal source code

■ ThreadLocal Definition

  • ThreadLocal provides an independent copy of the variable for each thread to solve the conflict of concurrent access to the variable.
  • When ThreadLocal is used to maintain a variable, ThreadLocal provides an independent copy of the variable for each thread that uses the variable. Therefore, each thread can change its own copy independently, without affecting the copies corresponding to other threads
  • In the ThreadLocal class, a Map is used to store copies of variables of each thread. The key of the element in the Map is the thread object, and the value corresponds to the variable copy of the thread.
  • ThreadLocal self-recognition: We can compare "hotel" to an application. Each room is a "sub-thread", and ThreadLocal is the person who provides services for each "room". They do not conflict with each other and remain independent.
  • After JDK1.5 introduced generics, ThreadLocal said goodbye to the Object era and entered the generic era.
  • A container that stores the private variables of a thread.
  • ThreadLocal is not designed to solve multi-thread access to shared variables, but to create a separate copy of variables for each thread. It provides an object-preserving method and avoids the complexity of parameter passing.

 

■ ThreadLocal Data Structure

1. Class Definition

public class ThreadLocal<T>

2. important internal elements

private final int threadLocalHashCode = nextHashCode();private static AtomicInteger nextHashCode = new AtomicInteger();private static final int HASH_INCREMENT = 0x61c88647;

3. Constructor

/** ThreadLocal only provides an empty default constructor, which is pure enough **/public ThreadLocal (){}

 

■ ThreadLocal Important Method

1. set () method

/*** Sets the current thread's copy of this thread-local variable to the specified value. * Most subclasses will have no need to override this method, relying solely on the * {@ link # initialValue} method to set the values of thread-locals. * set the local variable value of the current thread in the current ThreadLocal * its subclass does not need to override this method, you only need to override the initialValue method to set the initial default value. * @ param value the value to be stored in the current thread's copy of * this thread-loc Al. copy the current value to the local variable */public void set (T value) of the current Thread {// obtain the current Thread t = Thread. currentThread (); // obtain the Map ThreadLocalMap map = getMap (t) held by the current thread; // createMap or set directly if (map! = Null) // note that the key is this, which refers to the map of the ThreadLocal object that currently calls the set method. set (this, value); else // initialize its ThreadLocalMap based on the current thread and set the value createMap (t, value );}

2. get () method

/*** Returns the value in the current thread's copy of this thread-local variable. * If the variable has no value for the current thread, it is first initialized to * the value returned by an invocation of the {@ link # initialValue} method. * returns the local variable of the thread corresponding to the current thread in the current ThreadLocak * if the current value does not exist, returns the initial default value set by the initialValue Method * @ return the current thread's value of this thread-local */public T get () {// gets the current thread Threa D t = Thread. currentThread (); // obtain the Map ThreadLocalMap map held by the current Thread = getMap (t); if (Map! = Null) {ThreadLocalMap. Entry e = map. getEntry (this); if (e! = Null) return (T) e. value;} // If Map is null or the value is null, return the default value return setInitialValue ();}

3. remove () method

/*** Removes the current thread's value for this thread-local variable. * If this thread-local variable is subsequently {@ linkplain # get read} * by the current thread, its value will be reinitialized by invoking its * {@ link # initialValue} method, unless its value is {@ linkplain # set} * by the current thread in the interim. this may result in multiple invocations * of the {@ code initialValue} Method in the current thread. * remove the private variable corresponding to the current thread in the current ThreadLocal * When the variable is then read by the current thread (get ), this value will be re-initialized by the initialValue method unless set during this period * this will cause the initialValue method to be called multiple times by the current thread * @ since 1.5 this method is the newly added method of JDK */public void remove () {// obtain the ThreadLocalMap held by the current Thread. It can be seen that the code in get and set should also be merged into a line of ThreadLocalMap m = getMap (Thread. currentThread (); if (m! = Null) // note that the current ThreadLocal object (I .e. the key of ThreadLocalMap) removed from ThreadLocalMap m. remove (this );}

4. getMap, createMap Method

/**  * Get the map associated with a ThreadLocal. Overridden in  * InheritableThreadLocal.  *  * @param  t the current thread  * @return the map  */ThreadLocalMap getMap(Thread t) {    return t.threadLocals;}/**     * Create the map associated with a ThreadLocal. Overridden in     * InheritableThreadLocal.     *     * @param t the current thread     * @param firstValue value for the initial entry of the map     */void createMap(Thread t, T firstValue) {      t.threadLocals = new ThreadLocalMap(this, firstValue); }

5. nextHashCode Method

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

6. initialValue Method

/*** Returns the current thread's "initial value" for this thread-local variable. * This method will be invoked the first time a thread accesses the variable * with the {@ link # get} method, unless the thread previusly invoked the {@ link # set} * method, in which case the <tt> initialValue </tt> method will not be invoked for the thread. * Normally, this method is invoked at most once per thread, but it may be invoked again * in case of subsequent invocations of {@ link # remove} followed by {@ link # get }. * returns the initial default value of the current thread in the current ThreadLocal. * This method is called during the first get operation, unless the set Method (that is, the existing value) has been called before) * generally, this method is executed only once, but may occur multiple times, for example: * After the remove method is called, The get Method * <p> This implementation simply returns <tt> null </tt> is called; if the programmer desires * thread-local variables to have an initial value other than <tt> null </tt>, * <tt> ThreadLocal </tt> must be subclassed, and this method overridden. * Typically, an anonymous inner class will be used. * this method returns null by default. You can override this method (for example, inherit from or implement an anonymous class) * @ return the initial value for this thread-local */protected T initialValue () {return null;} ---------------/** for example, to customize a String-type anonymous ThreadLocal **/ThreadLocal <String> stringThreadLocal = new ThreadLocal <String> () {@ Override protected String initialValue () {return "I am roman ";}};

 

■ ThreadLocalMap-the secret of thread isolation

  • ThreadLocalMap is a special hash table specially designed for local variables of the thread.
  • The key of ThreadLocalMap is ThreadLocal, and value is the value of the variable to be saved.
  • Each thread has a private ThreadLocalMap object, which can store multiple key-value pairs with different ThreadLocal as the key.
  • ThreadLocalMap uses the open address method instead of the linked list to resolve conflicts, and requires the capacity to be a power of 2.

1. Class Definition

static class ThreadLocalMap

2. Entry

/*** The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object ). note that null keys (I. e. entry. get () * = null) mean that the key is no longer referenced, so the * entry can be expunged from table. such entries are referred to * as "stale entries" in the code that follows. * It uses the primary reference domain as its own key (I .e. ThreadLocal object) * because the Entry inherits from WeakR And ThreadLocal is encapsulated by WeakReference *!! Note: The Key of the Entry is weak reference (not Entry )!! (I will further elaborate on the memory leakage) * When the get method is called to return null, this means that the key is no longer referenced. Therefore, this entry will remove * weak references from the array: when JVM detects weak references during GC, it immediately recycles * It is interesting that the Entry does not use HashMap. the linked list structure of Entry * interested readers can first think about how ThreadLocalMap handles hash conflicts (which will be explained later) */static class Entry extends WeakReference <ThreadLocal <?> {/** The value associated with this ThreadLocal. */Object value; // when the external strong reference of ThreadLocal is recycled, the key of ThreadLocalMap will become null // note that the key is a ThreaLocal Object, but because the key is encapsulated by WeakReference, therefore, the Entry (ThreadLocal <?> K, Object v) {super (k); value = v ;}}

3. important internal elements

/*** The initial capacity -- MUST be a power of two. * The capacity must be a power of 2 and serve The Hash algorithm */private static final int INITIAL_CAPACITY = 16;/*** The table, resized as necessary. table. length MUST always be a power of two. * The underlying implementation is still an Entry array */private Entry [] table;/*** the number of entries in The table. * Number of existing elements in The array */private int size = 0;/*** The next size value at which to resize. * threshold. The Default value is 0 */private int threshold. // Default to 0

4. Constructor

/*** 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. * The default constructor contains a key-Value Pair: A ThreadLocal key, A value * createMap method of any type directly uses this constructor to instantiate ThreadLocalMap and store key-value pairs at a time */ThreadLocalMap (ThreadLocal firstKey, Object firstValue) {table = new Entry [INITIAL_CAPACITY]; // calculate the index of the array subscript and HashMap = key. hashCode () & (cap-1) is consistent (namely, the optimized version of the modulo operation) int I = firstKey. threadLocalHashCode & (INITIAL_CAPACITY-1); // fill in the array table [I] = new Entry (firstKey, firstValue) with the specified subscript in the array; size = 1; setThreshold (INITIAL_CAPACITY ); // the default threshold is 32/3 or equal to 10.6667}/*** Set the resize threshold to maintain at worst a 2/3 load factor. * Get len 2/3 instead of HashMap 0.75 */private void setThreshold (int len) {threshold = len * 2/3 ;}

5. Some important methods of ThreadLocalMap

1) set Method

/*** Set the value associated with key. * store key-value pairs. It is interesting that the Entry is not a linked list, which means that the underlying layer of ThreadLocalMap is only an array * It resolves conflicts (or hashes optimization) the key lies in the magic 0x61c88647 * If an expiration slot is encountered, the expiration slot will be occupied (the displacement and slot clearing operations will be involved) * When the cleaning is successful, the threshold value is reached at the same time, you need to resize * @ param key the thread local object * @ param value the value to be set */private void set (ThreadLocal key, Object value) {Entry [] tab = table; int len = tab. length; // array capacity // calculate the index of the array subscript and HashMap = key. hashCode () & (cap-1) Consistent (I .e. optimized modulo) int I = key. threadLocalHashCode & (len-1); for (Entry e = tab [I]; e! = Null; e = tab [I = nextIndex (I, len)]) {ThreadLocal k = e. get (); // if the key already exists, replace the value with if (k = key) {e. value = value; return;} // if the current slot is an expiration slot, clear and occupy the expiration slot if (k = null) {replaceStaleEntry (key, value, I ); return;} // otherwise, continue until the key is found to be equal or the first expiration slot is found.} tab [I] = new Entry (key, value); int sz = ++ size; // when the cleaning succeeds and the threshold value is reached, You need to scale up. // The amount of cleanSomeSlots to process is the number of existing elements if (! CleanSomeSlots (I, sz) & sz> = threshold) rehash ();}/*** Increment I modulo len. if the length is not exceeded, it will increase by 1 */private static int nextIndex (int I, int len) {return (I + 1 <len )? I + 1: 0 );}

2) remove Method

/*** Remove the entry for key. * When this element is found, two cleaning operations are performed. * 1. set key (ThreadLocal) to null * 2. the current slot changes to an expiration slot, so you need to clear the Entry elements stored in the current slot (mainly to avoid Memory leakage) */private void remove (ThreadLocal key) {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)]) {if (e. get () = key) {e. clear (); // The key is set to null-> this. referent = null expungeStaleEntry (I); // clear the expired element return ;}}}

 

■ Collision solution and magic 0x61c88647

  • Witty readers certainly find that ThreadLocalMap does not use a linked list or a red/black tree to solve the hash conflict. Instead, it only uses an array to maintain the entire hash table, so how to ensure the most important hash is a great test
  • ThreadLocalMap solves this problem by combining three clever designs:
    1. The key of the Entry is designed as a weak reference, so the key may be GC at any time (that is, the failure is fast), and as many empty slots as possible
    2. When a single ThreadLocal collision occurs, use the open address method for linear detection to solve the conflict problem.
    3. The magic 0x61c88647 is introduced (when multiple ThreadLocal threads are used) to enhance its hash and greatly reduce the collision probability.
  • The reason why this value is not used to accumulate is that it may be related to finding the nearest empty slot (skip lookup is more effective than auto increment 1 lookup to find the empty slot, because more available space spreading out is available, it is also related to its good hash.
/*** 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. * In order to ensure that the hash code can be evenly distributed in the n array of 2 */private static final int HASH_INCREMENT = 0x61c88647;/*** Returns the next hash code. * hashCode of each ThreadLocal is accumulated HASH_INCREMENT */private static int nextHashCode () {// the previous id + our magic number return nextHashCode. getAndAdd (HASH_INCREMENT );}

 

■ ThreadLocal Implementation Mechanism

  • Each thread has a ThreadLocalMap object, that is, ThreadLocal. ThreadLocalMap threadLocals = null.
  • Each ThreadLocal object has a unique HashCode generated during creation, that is, nextHashCode (). The modulo operation is used to determine the subscript position of the slot.
  • Access the value of a ThreadLocal variable, that is, find the corresponding key-Value Pair in ThreadLocalMap, that is, the key is the key-value pair of the ThreadLocal variable.
  • Since a ThreadLocalMap can have multiple ThreadLocal, we can derive that a thread can have multiple ThreadLocal (or have multiple key-value pairs with different ThreadLocal as the key)
// You can define multiple ThreadLocal, each thread has its own private various generic ThreadLocal // For example, thread A can simultaneously have the following three ThreadLocal objects as keyThreadLocal <String> stringThreadLocal = new ThreadLocal <String> (); threadLocal <Object> objectThreadLocal = new ThreadLocal <Object> (); ThreadLocal <Integer> intThreadLocal = new ThreadLocal <Integer> ();

 

PS:

* ***** I will discuss with you some practical problems about memory leakage and ThreadLocal. Please advise !! ************

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.