Java Concurrency --ThreadLocal

ThreadLocal

Outline

First, the understanding of ThreadLocal

1.1 ThreadLocal defined in the JDK

1.2 application scenarios

Second, in-depth analysis ThreaLocal class

2.1 get()

2.2 setIntialValue()

2.3 ThreadLocal class is how to create a copy of the variable for each thread

Three, ThreadLocal application scenarios

3.1 Database connectivity issues

3.2 Session Management

3.3 Thread-per-Request (corresponding to a request to a server thread)

Four, ThreadLocal general use step

Outline

This article draws on Java Concurrency in this blogger's column article, his column is very well written, it is recommended!


ThreadLocal known as thread-local variables in Java is a more special thread binding mechanism, you can provide a copy of a variable value for each thread to use the variable, and each thread can independently change their copy, and it does not conflict with a copy of the other threads.


In general, always relevant by accessing data ThreadLocal with the current thread, that is to say, JVM for each running thread binding the local instance of private space access, concurrent access problems so as to multi-threaded environment often appear It provides an isolation mechanism.


If a variable is a thread to be exclusive, then we can achieve local storage by ThreadLocal;


First, the understanding of ThreadLocal

1.1 ThreadLocal defined in the JDK

Each thread has its private value on the ThreadLocal variable, and the other thread is not visible;

ThreadLocal can be given independent of an initial value, so that each thread will get a copy of the initialization value, and each thread on the modified value to the other threads are not visible;

An important role is to class ThreadLocal is the state of the thread associated with them, the solution is to define a private static ThreadLocal instance in this class;

1.2 application scenarios

Class ThreadLocal main solution is for each thread to bind their value, in order to facilitate its handling their own state;


Figuratively speaking, ThreadLocal variables can be likened to a global box store data, the box can store private data for each thread. For example, the following classes for generating a unique local identifier for each thread. The thread ID is assigned when the first call uniqueNum.get (), does not change in subsequent calls;


Second, in-depth analysis ThreaLocal class

ThreadLocal in, provided a total of four methods:


public T get() { }

public void set(T value){ }

public void remove(){ }

protected T initialValue{ }

1

2

3

4

get () Gets ThreadLocal variables stored in the current thread value;

set () ThreadLocal set value of the current thread;

remove () to remove the current thread associated ThreadLocal variable;

the initialValue () is a protected method, generally need to be rewritten;

2.1 get()

Source as follows:


public T get(){

Thread t = Thread.currentThread (); // Get the current thread object

ThreadLocalMap map = getMap(t);

if(map!=null){

// get the thread-local variable corresponding entry from ThreadLocalMap current thread

ThreadLocalMap.Entry e = map.getEntry(this);

if(e!=null)

return (T) e.value; // obtain the target value

}

return setInitialValue();

}

1

2

3

4

5

6

7

8

9

10

11

2.2 setIntialValue()

private T setIntialValue(){

T value = initialValue (); // The default implementation returns null

Thread t = Thread.currentThread (); // get the current thread;

ThreadLocalMap map = getMap (t); // get the current thread ThreadLocalMap type field threadLocals

if(map!=null)

map.set (this, value); // this is the key map objects ThreadLocal

else 

createMap(t,value);

return value;

}

1

2

3

4

5

6

7

8

9

10

initialValue()


    protected T initialValue() {

        return null; // default implementation returns null

    }

1

2

3

createMap()


    void createMap(Thread t, T firstValue) {

        t.threadLocals = new ThreadLocalMap (this, firstValue); // this refers to the current ThreadLocal variable, as the map key  

    }

1

2

3

2.3 ThreadLocal class is how to create a copy of the variable for each thread

Each thread has an internal ThreadLocal.ThreadLocalMap member variable of type threadLocals, this threadLocals stores all ThreadLocal variables and their corresponding value ( "ThreadLocal variables and their corresponding value" is an Entry in the Map) associated with the thread . Key is ThreadLocal variable, Value is a variable corresponding to the value of the ThreadLocal;

Initially, inside threadlocals Thread empty, when the call ThreadLocal variable ** get () method or set () ** Thread class will be on the threadlocals initialized, and the current key ThreadLocal variables, to be saved to ThreadLocal value value, to keep ThreadLocals;

Then the current thread which, if you want to use ThreadLocal object can be obtained by the method threadLocals get the thread, and a bond to achieve the target ThreadLocal corresponding Value, i.e. the value stored in the object ThreadLocal;

Three, ThreadLocal application scenarios

Java, the class ThreadLocal variables are resolved between different threads of isolation. The most common usage scenarios have ThreadLocal database connection problems, Session management.


3.1 Database connectivity issues

private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {

    public Connection initialValue() {

        return DriverManager.getConnection(DB_URL);

    }

};


public static Connection getConnection() {

    return connectionHolder.get();

}

1

2

3

4

5

6

7

8

9

3.2 Session Management

private static final ThreadLocal threadSession = new ThreadLocal();


public static Session getSession() throws InfrastructureException {

    Session s = (Session) threadSession.get();

    try {

        if (s == null) {

            s = getSessionFactory().openSession();

            threadSession.set(s);

        }

    } catch (HibernateException ex) {

        throw new InfrastructureException(ex);

    }

    return s;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

3.3 Thread-per-Request (corresponding to a request to a server thread)

In the classical model of interactive Web, a processing request is basically "corresponds to a request to a server thread" approach, so the request can be provided in the form of ThreadLocal similar, so that when a server thread to process the request when, the process can be the exclusive request;


Four, ThreadLocal general use step

Use ThreadLocal step is generally divided into three steps:


Create a ThreadLocal objects threadXxx, used to hold objects between threads need to isolate the processing of xxx;

Acquiring a data access method to the isolation getXxx (), in the determination process, if the object is null when ThreadLocal should be new () to access an object type of isolation;

Thread class in the run () method, to be operated by obtaining getXxx () method of the data, which can ensure that each thread corresponds to a data object, at any time that the object of operation, do not intersect.

————————————————


Guess you like

Origin blog.51cto.com/14516511/2435173