ThreadLocal source code analysis, threadlocal source code
1. Overview
ThreadLocal, which can be understood as a local variable of a thread, is used to provide a copy of the variable value for every thread that uses the variable. Each thread can change its own copy independently, it does not conflict with copies of other threads.
How does ThreadLocal maintain copies of variables for each thread?
Each Thread has a ThreadLocalMap (Thread. threadLocals) used to store copies of the variables of each Thread.
ThreadLocalMap uses the array Entry [] table to save the ThreadLocal --> Object key value Object. The storage position of the array is int I = key. nextHashCode () & (table. length-1 );.
ThreadLocal and Synchonized:
All are used to solve multi-thread concurrent access. Synchronized is used for data sharing between threads (so that a variable or code block can only be accessed by one thread at a time). It is a policy to extend the access time in exchange for thread security; threadLocal is used for data isolation between threads (providing copies of variables for each thread). It is a policy that exchanges space for thread security.
2. ThreadLocalMap
Used to store copies of variables of each thread
/** * ThreadLocalMap is a customized hash map suitable only for * maintaining thread local values. No operations are exported * outside of the ThreadLocal class. The class is package private to * allow declaration of fields in class Thread. To help deal with * very large and long-lived usages, the hash table entries use * WeakReferences for keys. However, since reference queues are not * used, stale entries are guaranteed to be removed only when * the table starts running out of space. */ static class ThreadLocalMap { /** * 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. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }/** * The table, resized as necessary. * table.length MUST always be a power of two. */ private Entry[] table; /** * 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); }/** * Get the entry associated with key. This method * itself handles only the fast path: a direct hit of existing * key. It otherwise relays to getEntryAfterMiss. This is * designed to maximize performance for direct hits, in part * by making this method readily inlinable. * * @param key the thread local object * @return the entry associated with key, or null if no such */ private Entry getEntry(ThreadLocal<?> key) { int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); } /** * Version of getEntry method for use when key is not found in * its direct hash slot. * * @param key the thread local object * @param i the table index for key's hash code * @param e the entry at table[i] * @return the entry associated with key, or null if no such */ private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) { Entry[] tab = table; int len = tab.length; while (e != null) { ThreadLocal<?> k = e.get(); if (k == key) return e; if (k == null) expungeStaleEntry(i); else i = nextIndex(i, len); e = tab[i]; } return null; } /** * 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(); } /** * Remove the entry for key. */ 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(); expungeStaleEntry(i); return; } } } ...... }
3. ThreadLocal
Public class ThreadLocal <T> {/*** ThreadLocals rely on per-thread linear-probe hash maps attached * to each thread (Thread. threadLocals and * inheritableThreadLocals ). the ThreadLocal objects act as keys, * searched via threadLocalHashCode. this is a custom hash code * (useful only within ThreadLocalMaps) that eliminates collisions * in the common case where consecutively constructed ThreadLocals * Are used by the same threads, while remaining well-behaved in * less common cases. */private final int threadLocalHashCode = nextHashCode ();/*** The next hash code to be given out. updated atomically. starts at * zero. */private static AtomicInteger nextHashCode = new AtomicInteger ();/*** The difference between successively generated hash codes-turns * implicit sequential thread-local I Ds into near-optimally spread * multiplicative hash values for power-of-two-sized tables. */private static final int HASH_INCREMENT = 0x61c88647;/*** Returns the next hash code. */private static int nextHashCode () {return nextHashCode. getAndAdd (HASH_INCREMENT);}/*** Returns the current thread's "initial value" for this * thread-local variable. this method will be invoked the first * time Thread accesses the variable with the {@ link # get} * method, unless the thread previously invoked the {@ link # set} * method, in which case the {@ code initialValue} 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 }. ** <p> This implement Ation simply returns {@ code null}; if the * programmer desires thread-local variables to have an initial * value other than {@ code null }, {@ code ThreadLocal} must be * subclassed, and this method overridden. typically, an * anonymous inner class will be used. ** @ return the initial value for this thread-local * // the initial value of the current thread that returns the local variable of this thread protected T initialValue () {return null ;} /*** Returns the va Lue 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. ** @ return the current thread's value of this thread-local * // return the value of public T get () in the current thread copy of the local variable of this thread () {Thread t = Thread. currentThread (); ThreadLocalMap map = t. threadLocals; if (Map! = Null) {ThreadLocalMap. Entry e = map. getEntry (this); if (e! = Null) {@ SuppressWarnings ("unchecked") T result = (T) e. value; return result;} return setInitialValue ();}/*** 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. ** @ param value the value to be stored in Current thread's copy of * this thread-local. * /// set the value in the current Thread copy of the local variable of this Thread to the specified value public void set (T value) {Thread t = Thread. currentThread (); ThreadLocalMap map = t. threadLocals; if (map! = Null) map. set (this, value); else createMap (t, value);}/*** 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 r Esult in multiple invocations of the * {@ code initialValue} method in the current thread. ** @ since 1.5 * // remove the value of the local variable of this Thread public void remove () {ThreadLocalMap m = Thread. currentThread (). threadLocals; if (m! = Null) m. remove (this);}/*** 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 );}......}
Why HASH_INCREMENT = 0x61c88647?
(Read Why 0x61c88647 ?)
Origin:
This number represents the golden ratio (sqrt (5)-1) times two to the power of 31. the result is then a golden number, either 2654435769 or-1640531527. you can see the calculation here:
long l1 = (long) ((1L << 31) * (Math.sqrt(5) - 1)); //Math.sqrt(5) - 1 = 1.2360679774997898System.out.println("as 32 bit unsigned: " + l1); //2654435769 int i1 = (int) l1;System.out.println("as 32 bit signed: " + i1); //-1640531527 = -0x61c88647
It is related to the fibonacci hashing (fibonacci hash) and golden division. The special hash code 0x61c88647 greatly reduces the collision probability and allows the hash code to be evenly distributed in the n array of 2.
Key. threadLocalHashCode & (len-1), the size of Entry [] table in ThreadLocalMap must be Npower of 2 (len = 2 ^ N ), the binary representation of the len-1 is the low continuous N 1, the key. the value of threadLocalHashCode & (len-1) is the low N Bit Of threadLocalHashCode.
Test:
private static AtomicInteger nextHashCode = new AtomicInteger(); private static final int HASH_INCREMENT = 0x61c88647; private static int nextHashCode() { return nextHashCode.getAndAdd(HASH_INCREMENT); } public static void main(String[] args) { for (int j = 0; j < 5; j++) { int size = 2 << j; // hash = 0; int[] indexArray = new int[size]; for (int i = 0; i < size; i++) { indexArray[i] = nextHashCode() & (size - 1); } System.out.println("indexs = "+ Arrays.toString(indexArray)); } }
Result:
Indexs = [0, 1]
Indexs = [2, 1, 0, 3]
Indexs = [2, 1, 0, 7, 6, 5, 4, 3]
Indexs = [2, 9, 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11]
Indexs = [18, 25, 0, 7, 14, 21, 28, 3, 10, 17, 24, 31, 6, 13, 20, 27, 2, 9, 16, 23, 30, 5, 12, 19, 26, 1, 8, 15, 22, 29, 4, 11]
If the duplicate index value is not displayed, and the hash table size is the N power of 2, the index value calculated each time will not be repeated.
Why does HashCode not directly use the auto-increment method (HASH_INCREMENT = 1 )?
In my understanding, as the unused ThreadLocal variable is recycled, the performance of this auto-increment method will get worse, because the near slot is very unlikely to be empty. ThreadLocal is actually used, and its subscript is in the skip distribution, so that even if there is a conflict, it is more likely to find the empty slot near, and the performance will be better.
4. Example
Implementation of Android Logoff:
public final class Looper {
...... // sThreadLocal.get() will return null unless you've called prepare(). static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } /** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static Looper myLooper() { return sThreadLocal.get(); }
......}
ThreadId:
Maintain the id of each thread
public class ThreadId { // Atomic integer containing the next thread ID to be assigned private static final AtomicInteger nextId = new AtomicInteger(0); // Thread local variable containing each thread's ID private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>(){ @Override protected Integer initialValue () { return nextId.getAndIncrement(); } }; // Returns the current thread's unique ID, assigning it if necessary public static int get() { return threadId.get(); } }