ThreadLocal Usage Details

Source: Internet
Author: User

ThreadLocal Usage Details
What is ThreadLocal? According to the explanation in the JDK document:

ThreadLocal is used to provide local variables in the thread. This variable can be accessed in a multi-threaded environment to ensure the independence of variables in each thread.

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 the copy of the variable independently, it does not affect the copies corresponding to other threads.

ThreadLocal usage:

We can see that we use ThreadLocal to store a String. After setting values in different threads, it only works in the current thread. So, as mentioned above

A ThreadLocal can be shared by multiple threads. Each thread can perform the set get operation on the same ThreadLocal only for the current thread.

I have probably learned how to use ThreadLocal. How does ThreadLocal ensure the independence of different threads?

ThreadLocal internal methods Protected T initialValue ()(If you do not want the initial value to return null, You need to override the initialValue method)
protected T initialValue() {    return null;}

Public T get ()(This method returns a copy of the current thread variable. If this is the first time the thread calls this method, this copy is created and initialized .)


 * 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. * * @return the current thread's value of this thread-local */public T get() {    Thread t = Thread.currentThread();    ThreadLocalMap map = getMap(t);    if (map != null) {        ThreadLocalMap.Entry e = map.getEntry(this);        if (e != null)            return (T)e.value;    }    return setInitialValue();}
Public void set (T value)


 * 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 the current thread's copy of *        this thread-local. */public void set(T value) {    Thread t = Thread.currentThread();    ThreadLocalMap map = getMap(t);    if (map != null)        map.set(this, value);    else        createMap(t, value);}
From the get and set source code, we can see that data access is to obtain the ThreadLocalMap object first ThreadLocalMapAccess ThreadLocalMap is a map, and its key is threadLocal itself. The value is the copy of the stored variables. Each thread corresponds to a map of a local variable, and each thread can store multiple local variables (that is, different ThreadLocal) Public void remove ()(Jdk1.5 appears later)


 * 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 set} by the current thread * in the interim.  This may result in multiple invocations of the * initialValue method in the current thread. * * @since 1.5 */ public void remove() {     ThreadLocalMap m = getMap(Thread.currentThread());     if (m != null)         m.remove(this); }

You can see through the remove source code,

First obtain the ThreadLocalMap of the current Thread through the getMap (Thread. currentThread () method of ThreadLocal, and then get, set, remove in the ThreadLocalMap of the current Thread

What are the points you need to know about remove:

Why to remove a ThreadLocal value:

The purpose is to reduce the memory cache. If the local variable value of this thread is accessed again after the removal, the initial initiValue will be returned.

After the thread ends, all local variables corresponding to the thread will be automatically reclaimed by garbage collection. However, it is displayed that calling remove is clear that the local variables of the thread are not required, but it can speed up memory collection.

ThreadLocal: the difference between the synchronization mechanism and synchonzied ThreadLocal: Change space for time synchonzied: Change space for time

Synchonzied synchronization mechanism:

Multi-threaded concurrent access control for the same resource ensures data sharing among multiple threads,Synchronization brings huge performance overhead, so the synchronization operation should be fine-grained (different elements in the object use different locks, rather than a lock of the entire object), In the case of time for space, it means:The real risk of using synchronization is complexity and the possibility of compromising resource security, rather than performance.

ThreadLocal Thread Local variable mechanism:

In exchange for space time, different threads access the same ThreadLocal, and data access is a copy of the data of the current thread. That is to say, different threads access not the same object at a time, so the efficiency is relatively high, however, the memory usage is relatively large. When the thread ends, removing will speed up memory recovery.

Synchronized focuses on data sharing between threads, while ThreadLocal focuses on data isolation between threads.

ThreadLocal disadvantages (Memory leakage) Causes of Memory leakage

ThreadLocalMap uses the weak reference of ThreadLocal as the key. If a ThreadLocal does not have a strong external reference, the ThreadLocal will be recycled during system GC.

After ThreadLocal is recycled, the Entry with the key being null will appear in the middle of ThreadLocalMap of the current Thread.

If the key is null, it means that there is no way to access the values corresponding to these keys, and the following strong reference chain will exist:


Memory leakage solution

This situation has been taken into account in the ThreadLocalMap design, and some protection measures have been added:ThreadLocalGet (),Set (),The thread will be cleared when removing ().AllKey isNullvalue。

The following operations may cause memory leakage:

Use static ThreadLocal to extendThreadLocal lifecycle, resulting in the end of a Thread, but ThreadLocalMap in the Thread contains this static ThreadLocal, resulting in ThreadLocalMap being unable to be recycled, resulting in the Thread being unable to be recycled

Allocated and usedThreadLocal is no longer calledGet (),Set (),The remove () method causes memory leakage. Because

Get (),Set (),Remove () clears all null key values in ThreadLocalMap.

ThreadLocal in Android Handler message mechanism

Anyone familiar with the Handler mechanism knows

Lorule. preparemainlorule () in the main method of ActivityThread; or lorule. pepare () in the thread created by myself

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));}

Creates a logoff object and saves it using the sThreadLocal set method.

The ThreadLocal is static in the logoff class, as shown below:

That is to say, this static ThreadLocal can be accessed by any thread, but the logoff obtained from any thread is only a local variable of the thread, all of which are in copies.

Therefore, each thread corresponds to a logoff,

For the summary of ThreadLocal, I will sort it out here for the time being. Will it be added later?

Related Article

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: 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.