Thread local variable threadlocal

Source: Internet
Author: User
Tags static class

PS:

About multithreaded shared variables threadlocal<t>

The share of a variable value can be in the form of a public static variable, and all threads can use the same public static variable. If you want to implement each thread has its own shared variables, how to implement. A class threadlocal<t> is provided in the JDK to solve such problems.

principle:
ThreadLocal-Owning Package java.lang.threadlocal<t> is a generic class
Threadlocal provides a new idea for solving multithreading concurrency problems, and using this class library can be implemented in a simple way,
When using threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so no thread can change its own copy without affecting the other thread's copy of the variable.
From a thread's point of view, the target variable is like a thread's local variable, which is what the "locals" in the class name means.

Threadlocal the principle of maintaining a copy of a variable for each thread: in the Threadlocal class, there is a map collection that stores a copy of the variable for 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. View the threadlocal source can see
The main methods of its openness are:
Public T Get () returns the thread local variable for the current thread.
The public void set (T value) sets the value of the thread local variable for the current thread.
The public Void Remove () deletes the value of the current thread local variable in order to reduce memory consumption, note (when the thread is finished, the local variable that should thread will automatically be garbage collected, so it is not necessary to explicitly call the method to purge the thread's local variables. But it can speed up memory recovery)

Public static <S> threadlocal<s> withinitial (supplier<? extends s> Supplier) initialization value


Set (T value) When you create a variable setting value, you can see that the Threadlocalmap class is used, which is a static inner class in the threadlocal

  /**
     * Sets The current thread's copy of this thread-local variable * to the
     specified value.  Most subclasses'll have no need
     to * Override this method, relying solely on the {@link #initialValue}
     * To set the values of Thread-locals.
     *
     * @param value of the value of "stored in" the current thread ' s copy of
     *        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);
    

  /**
     * Sets The current thread's copy of this thread-local variable * to the
     specified value.  Most subclasses'll have no need
     to * Override this method, relying solely on the {@link #initialValue}
     * To set the values of Thread-locals.
     *
     * @param value of the value of "stored in" the current thread ' s copy of
     *        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);
    

Threadlocalmap is used to store variable copies 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 is removed only when * the table
     Starts running out of the 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's the key is no longer referenced, so the * ent  Ry can is 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 th Is ThreadLocal.

            */Object value;
                Entry (threadlocal<?> K, Object v) {super (k);
            Value = V; }
        }

... Omit ...}


Example:

1, create two threads to implement variable storage

The public class Threada extends thread {public

	void run () {
		/) sets the variable value to the current thread
		ThreadLocalTool.THREAD_LOCAL.set (" threada:["+ math.random () +"] ");
		Output
		System.out.println ("Get Threada:" + ThreadLocalTool.THREAD_LOCAL.get ());
	}

The public class Threadb extends thread {public

	void run () {
		/) sets the variable value to the current thread
		ThreadLocalTool.THREAD_LOCAL.set ( "threadb:[" + math.random () + "]");
		Output
		System.out.println ("Get threadb:" + ThreadLocalTool.THREAD_LOCAL.get ());
	}


2. Run Test Client

public class Client {public

	static void Main (string[] args) {
		Threada TA = new Threada ();
		THREADB TB = new threadb ();
		Sets the variable value to the current thread
		ThreadLocalTool.THREAD_LOCAL.set ("main:[" + math.random () + "]");

		Ta.start ();
		Tb.start ();

		SYSTEM.OUT.PRINTLN ("Get main:" + ThreadLocalTool.THREAD_LOCAL.get ());
	}

After the above example runs, the output:

Get main:main:[0.7622350866507818]
Get threadb:threadb:[0.6860560404190107]
Get threada:threada:[0.22195491171797677]

It can be seen that the Threadlocal class solves the problem of the isolation of variables between different threads, that is, different threads use their own values, and the values of different threads can be stored in threadlocal.


Advantages of Threadlocal

What are the advantages of threadlocal versus thread synchronization mechanisms? Both threadlocal and thread synchronization mechanisms are designed to resolve access violations of the same variables in multiple threads.
1 in the synchronization mechanism, the lock mechanism of the object ensures that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when the need to lock an object, when the release of object locks and other complex problems, programming and writing difficulty is relatively large.
2) and threadlocal from another angle to solve the multithreading of concurrent access. Threadlocal provides a separate copy of the variable for each thread, isolating multiple threads from accessing the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides a thread-safe shared object that can encapsulate unsafe variables into threadlocal when writing multithreaded code.
3) To sum up, for multi-threaded resource sharing problem, synchronization mechanism adopted the "time for space" approach, and threadlocal adopted the "space to change time" approach. The former provides only one variable, allowing different threads to be queued for access, and the latter provides a variable for each thread so that it can be accessed simultaneously without affecting each other.













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.