Threadlocal (implementing Multi-threaded synchronous access variables)

Source: Internet
Author: User

Threadlocal translated into Chinese the more accurate term should be: thread local variables.

What's the use of this thing, or why do you have one? First of all, in concurrent programming, member variables if you do not do any processing is actually thread insecure, each thread is operating the same variable, it is obviously not possible, and we also know that the volatile keyword is not guaranteed thread-safe. So in one case, we need to meet a condition where the variable is the same, but each thread uses the same initial value, that is, a new copy of the same variable. In this case threadlocal is very much used, such as DAO's database connection, we know that DAO is a singleton, then his attribute connection is not a thread-safe variable. And each of us needs to use him, and each one uses its own. In this case, threadlocal a better solution to the problem.

We analyze this problem from the perspective of source code.

First define a threadlocal:

123456789101112131415161718 public class ConnectionUtil {    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();    private static Connection initConn = null;    static {        try {            initConn = DriverManager.getConnection("url, name and password");        } catch (SQLException e) {            e.printStackTrace();        }    }        public Connection getConn() {        Connection c = tl.get();        tl.set(initConn);        return c;    }    }

In this way, the same connection is used, but each connection is new and a copy of the same connection.

So how is the implementation mechanism?

1, each thread object inside has maintained a threadlocalmap such a threadlocal map, can hold a number of threadlocal.

123 /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ThreadLocal.ThreadLocalMap threadLocals = null;

2, when we call the Get () method, get the current thread, and then get to the current thread of the Threadlocalmap object, if not NULL, then remove the value of threadlocal, otherwise initialized, Initialization is to set the value of InitialValue to threadlocal.

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

3, when we call the set () method, very general, is to set the value into the threadlocal.

4, Summary: When we call the Get method, in fact, each current thread has a threadlocal. Each fetch or setting is an operation on the threadlocal that is separate from the other threads.

5. Application scenario: When many threads need to use the same object multiple times and need the same initialization value for the object, it is best to use threadlocal.

6, actually say more also than look at the source code come clear. If you want to see the source code, which involves a weakreference and a map, these two places need to understand, these two things are a. Java's weak reference, that is, the GC will destroy the reference to the object wrapped (referenced), the threadlocal as a key may be destroyed, but as long as we define his class does not unload, TL this strong reference will always refer to this threadlocal, will never be GC off. B. Similar to the HashMap.

In fact, essentially, each thread maintains a map, and the key of the map is threadlocal, and the value is the value of our set, and each time the thread is in the get, it takes the value from its own variable, and since it takes a value from its own variable, There's no such thing as a thread-safety problem, in general, the state of the threadlocal variable doesn't change at all, he just acts as a key and provides an initial value for each thread. If we allow it, we can do it ourselves, except that the JDK has helped us do it.

Threadlocal (implementing Multi-threaded synchronous access variables)

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.