Improve scalability with ThreadLocal
The ThreadLocal class quietly appeared in Java platform version 1.2. Although the support for Thread Local variables is early part of many thread tools (such as Posix pthreads), the original design of Java Threads API did not provide this useful feature. Moreover, the initial implementation was quite inefficient. For these reasons, ThreadLocal is seldom noticed, but it is very convenient for simplifying the development of thread-safe concurrent programs. Brian Goetz, Java software consultant, has studied ThreadLocal and provided some tips for using it.
Join Brian's multi-threaded Java programming forum to get help on thread and concurrency issues in your project.
It is difficult to write thread security classes. It not only requires careful analysis of the conditions under which variables can be read and written, but also requires careful analysis of how other classes can use a class. Sometimes it is very difficult to make the class thread safe without affecting the function, usability, or performance of the class. Some Classes retain the state information from a method call to the next method call. In practice, it is difficult to make such classes thread-safe.
It is easier to manage non-thread security classes than to try to make classes thread-safe. Non-thread security classes can be safely used in multi-threaded programs, as long as you can ensure that the instances of classes used by one thread are not used by other threads. For example, the JDBC Connection class is non-thread-safe-two threads cannot securely share a Connection at a small granularity-but if each thread has its own Connection, then multiple threads can perform database operations safely at the same time.
It is certainly possible to maintain a separate JDBC connection (or any other object) for each Thread without using ThreadLocal. The Thread API gives us all the tools needed to connect objects with threads. ThreadLocal makes it easier for us to successfully associate a thread with its per-thread data.
What is thread-local variable )?
Thread Local variables efficiently provide a copy of the local variable values of individual threads for each thread that uses it. Each thread can only see the values associated with itself, without knowing that other threads may be using or modifying their own copies. Some compilers (such as Microsoft Visual C ++ compiler or ibm xl fortran compiler) use storage class modifiers (such as static or volatile) to integrate support for local variables in the thread into their language. The Java compiler does not provide special language support for local variables of the Thread. On the contrary, it uses the ThreadLocal class to implement these support. The Core Thread class has special support for this class.
Because local variables in the thread are implemented through a class, rather than being part of the Java language itself, therefore, the syntax for using local variables in the Java language is more clumsy than that of the built-in local variable language. To create a thread local variable, instantiate an object of ThreadLocal class. The behavior of the ThreadLocal class is similar to that of various Reference classes in java. lang. ref. The ThreadLocal class acts as an indirect handle for storing or retrieving a value. Listing 1 shows the ThreadLocal interface.
Listing 1. ThreadLocal Interface
Public class ThreadLocal {
Public Object get ();
Public void set (Object newValue );
Public Object initialValue ();
}
Get () accessors retrieve the value of the current thread of the variable; set () accessors modify the value of the current thread. The initialValue () method is optional. If a variable is not used by the thread, you can use this method to set the initial value of the variable. It allows delayed initialization. It is best to use an example to illustrate how ThreadLocal works. Listing 2 shows an implementation method of ThreadLocal. It is not a particularly good implementation (although it is very similar to the initial implementation), so it is likely to have poor performance, but it clearly shows how ThreadLocal works.
Listing 2. Poor ThreadLocal implementation
Public class ThreadLocal {
Private Map values = Collections. synchronizedMap (new HashMap ());
Public Object get (){
Thread curThread = Thread. currentThread ();
Object o = values. get (curThread );
If (o = null &&! Values. containsKey (curThread )){
O = initialValue ();
Values. put (curThread, o );
}
Return o;
}
Public void set (Object newValue ){
Values. put (Thread. currentThread (), newValue );
}
Public Object initialValue (){
Return null;
}
}
The performance of this implementation is not very good, because every get () and set () operations require synchronization on the values ing table, And if multiple threads simultaneously access the same ThreadLocal, then competition will occur. In addition, this implementation is impractical, because the keyword in the values ing table using the Thread object will not be able to recycle the Thread after the Thread exits, in addition, the ThreadLocal value of the dead thread cannot be garbage collected.
Use ThreadLocal to implement Singleton per Thread
Thread Local variables are often used to depict stateful Singleton or thread-safe shared objects, or encapsulate insecure variables into ThreadLocal, or encapsulate the thread-specific state of the object into ThreadLocal. For example, in applications closely related to databases, many methods of the program may need to access the database. It is inconvenient to include a Connection in each method of the system as a parameter-using a "list" to access the Connection may be a more rough but convenient technology. However, multiple threads cannot securely share a JDBC Connection. As shown in listing 3, by using ThreadLocal in the "list", we can make it easy for any class in our program to obtain a reference of each thread Connection. In this way, we can think that ThreadLocal allows us to create a thread list.
Listing 3. Store a JDBC connection to a Singleton thread
Public class ConnectionDispenser {
Private static class ThreadLocalConnection extends ThreadLocal {
Public Object initialValue (){
Return DriverManager. getConnection (ConfigurationSingleton. getDbUrl ());
}
}
Private ThreadLocalConnection conn = new ThreadLocalConnection ();
Public static Connection getConnection (){
Return (Connection) conn. get ();
}
}
Any State-or non-thread-safe object that is relatively more expensive than the use cost, such as JDBC Connection or regular expression matching, can use a single thread list (singleton) A good place for technology. Of course, you can use other technologies such as pools to securely manage shared access. However, from the perspective of scalability, even the pool has some potential defects. Because the pool implementation must use synchronization to maintain the integrity of the data structure of the pool. If all threads use the same pool, in the system where many threads frequently access the pool, program performance will be reduced due to Contention.
Simplify debugging log records with ThreadLocal
Other applications that are suitable for ThreadLocal but cannot be well replaced by the pool include applications that store or accumulate context information for each thread for later retrieval. For example, suppose you want to create a tool for managing debugging information of multi-threaded applications. You can use the DebugLogger class shown in Listing 4 as a local thread container to accumulate debugging information. At the beginning of a work unit, you clear the container, and when an error occurs, you query the container to retrieve all debugging information generated so far for this work unit.
Listing 4. Use ThreadLocal to manage debugging logs for each thread
Public class DebugLogger {
Private static class ThreadLocalList extends ThreadLocal {
Public Object initialValue (){
Return new ArrayList ();
}
Public List getList (){
Return (List) super. get ();
}
}
Private ThreadLocalList list = new ThreadLocalList ();
Private static String [] stringArray = new String [0];
Public void clear (){
List. getList (). clear ();
}
Public void put (String text ){
List. getList (). add (text );
}
Public String [] get (){
Return list. getList (). toArray (stringArray );
}
}
In your code, you can call DebugLogger. put () to save information about what your program is doing, and, if necessary later (for example, an error occurs), you can easily retrieve debugging information related to a specific thread. This technology is much easier than simply dumping all the information to a log file and then trying to find out which log records come from which thread (and worry about thread contention for log record objects, and more effective.
ThreadLocal is also useful in servlet-based applications or worker units that are a whole request to any multi-threaded application server, because a single thread is used throughout the request processing process. You can use the ThreadLocal variable to store context information for each request (per-request) using the thread-per-list technique described earlier.
The thread security of ThreadLocal is slightly poor, InheritableThreadLocal
The ThreadLocal class has a relative, InheritableThreadLocal, which works in a similar way, but applies to applications of different types. If the values of all InheritableThreadLocal objects are saved when a thread is created, these values are automatically passed to the subthread. If a subthread calls the get () of InheritableThreadLocal, it will see the same object as its parent thread. To protect thread security, you should only use InheritableThreadLocal for immutable objects (the State will never be changed once they are created) because the objects are shared by multiple threads. InheritableThreadLocal is suitable for transmitting data from the parent thread to the sub-thread, for example, user id or transaction id, but cannot be a stateful object, such as JDBC Connection.
ThreadLocal Performance
Although thread local variables have long been well-known and supported by many multi-threaded frameworks including Posix pthreads specifications, they were omitted in the original Java thread design, only added in Java 1.2