Java Concurrency (iii) threadlocal keywords

Source: Internet
Author: User

Theadlocal is called thread-local storage, which means that a variable, each thread has a copy of it, and is independent of each other.

Implementation of the Threadlocal class

Here are a few of the key methods that the class provides:

publicget() { }publicvoidsetvalue) { }publicvoidremove() { }protectedinitialValue() { }

By looking at the source code for that class in the JDK, you can see the implementation of the above method in general, where:

/** * Returns theValueinch  theCurrent thread ' sCopy  ofThis * thread-LocalVariable. If theVariable has no value for  the* Current Thread,it  is  FirstInitialized to  theValue returned * byAn invocation of  the{@link#initialValue} method.*     * @return  theCurrent thread ' s value ofThis thread-Local*/Public TGet() {Thread t = thread.currentthread (); Threadlocalmap map = getmap (t);if(map! = null) {Threadlocalmap.entry E = map.getentry (this);if(E! = null) {@SuppressWarnings ("Unchecked") Tresult= (T) e.value;return result; }        }returnSetinitialvalue (); }

is the implementation of the Get () method, first of all through a getmap get threadlocalmap, and then in this threadlocalmap through this to obtain the corresponding value as the return value: if you consider threadlocalmap as a map, We can see that the key to this map is actually the current Threadloca variable.
Next look at the implementation of the Getmap 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;    }

is actually returning the member variable threadlocals of the thread T, which is a threadlocalmap type.

So we can summarize how theadlocal works: There is a threadlocalmap map-like data structure attached to each thread, and the key to this data structure is the threadlocal variable that we define. At the same time we can define multiple threadlocal variables as key for this map.
Graphically expressed as:

From this point of view, threadlocal is just the equivalent of declaring that a type is thread-local storage, and that the actual data is stored in the member variable of each thread instance. This is the source of the thread-local storage name-the data is actually stored in the local thread.
There are also set:

/** * Sets theCurrent thread ' sCopy  ofThis thread-LocalVariable * to  theSpecified value. Most subclasses would have no need to* Override this method, relying solely on  the{@link#initialValue}* Method to Set  theValues ofThread-locals. * * @param value theValue tobe storedinch  theCurrent thread ' sCopy  of* This thread-Local. */public voidSet(T value)        {Thread T = thread.currentthread (); Threadlocalmap map = getmap (t);if(map! = null) map.Set(this, value);ElseCreatemap (t, value); }

Used to modify value values.

Also note that the inner class entry in Threadlocalmap is declared as WeakReference, which is one of four reference types in Java. Through related books and Web pages, Brief introduction:
Strongreference, which is a reference that we usually get in the form of new object (), is called a strong reference, and the GC does not reclaim the corresponding object as long as the strong reference is still there.
SoftReference, soft references, the system cleans up objects of this type of reference before the memory is going to overflow. For example, an external data source: A file, a database, a network, etc. can be declared as a reference to that type.
WeakReference, weak references, objects that are associated with weak references that are recognized by the JVM as weak can be recycled at the next GC.
The difference between SoftReference and WeakReference is that GC time is postponed as much as possible.
Phantom, virtual Reference. A virtual reference cannot be used to obtain an object instance, and the only purpose is to get a system notification when the object is reclaimed.

Threadlocal Application Scenarios

Database connection, session management, etc.

Java Concurrency (iii) threadlocal keywords

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