Threadlocal design and use

xiaoxiao2021-03-06  64

As early as Java 1.2 is launched, a new support is introduced in the Java platform: java.lang.threadlocal, gives us a new option when writing multithreaded programs. Using this tool class can be very simple to write beautiful multi-threaded programs, although Threadlocal is very useful, it seems to be understood now, and there are not many friends using it.

What is threadlocal?

What is threadlocal? In fact, Threadlocal is not a remote version of a thread, which is not a Thread, but thread local variable (thread local variable). Maybe named it to Threadlocalvar is more appropriate. Threadlocal actually function is very simple, which provides a copy of a variable value for each thread using the variable, and every thread can independently change its own copy, not a copy of other threads. conflict. From the perspective of the thread, it seems that each thread has this variable. Thread local variables are not Java's new invention, and in other language compilers (such as IBM XL Fortran), it provides direct support in the language level. Because Java did not provide direct support in the language level, but provided a THReadLocal class to provide support, so the code to write the wires in Java is relatively awkward, which may be that the thread local variable is not available in Java. A reason for a very good popularity.

Threadlocal design

First look at the interface of Threadlocal:

Object get (); // Returns the thread local variable copy protected object initialvalue (); // Returns the initial value VOID SET (Object value) of the current thread of the thread local variable; // Set the thread local variable of the current thread Copy value

Threadlocal has three methods, which is worth noting that initialvalue (), which is a protected method, apparently implemented for subclass rewriting. This method returns the initial value of the current thread at the primary variable of the thread, which is a delay calling method, and is executed when a thread is first calling GET () or set (Object), and only once. The real implementation in Threadlocal returns a NULL:

Protected Object InitialValue () {return null;}

How do Threadlocal maintains a copy of each thread maintenance variable? In fact, the idea of ​​achieving is very simple, there is a map in the Threadlocal class, which is used to store copies of the variables of each thread. For example, the following example 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 ()) {o = initialvalue (); value ,.put (curnetread, o);} returno}

Public void set (Object newValue) {VALUES.PUT (thread.currentthread (), newvalue);}

Public Object InitialValue () {return null;}} Of course, this is not an industry intensity, but the overall idea of ​​Threadlocal in JDK is also similar to this.

THREADLOCAL

If the thread local variable is desired to initialize other values, you need to implement the subclass of Threadlocal and rewrite the method, usually use an internal anonymous class to subclassify Threadlocal, such as the example below, the serialnum class assigns a serial number for each class :

Public class serialnum {// the next serial number to be assigned

Private static int nextserialnum = 0; private static threadlocal serialnum = new threadlocal () {protected synchronized Object initialvalue () {Return New Integer (NEXTSERIALNUM );}}

Public static int GET () {Return ((Integer))). INTVALUE ();}}

The use of the Serialnum class will be very simple, because the get () method is static, so simply call when the serial number of the current thread is required:

INT serial = serialnum.get ();

I.e.

When the thread is active and the ThreadLocal object is accessible, the thread holds an implicit reference to the local variable copy of the thread, and after the thread runs, the thread has a copy of the thread local variable. Failure, and wait for the garbage collector to collect.

Comparison of Threadlocal and other synchronization mechanisms

What is the advantage over ThreadLocal and other synchronization mechanisms? Threadlocal and all other synchronization mechanisms are to solve the access conflict of the same variable in multi-threads. In the normal synchronization mechanism, it is a safe access to the same variable through object locking. At this time, the variable is a plurality of thread sharing. It is necessary to analyze when using this synchronization mechanism to read and write the variables. When is it necessary to lock an object, when it releases a lot of locks. All of this is due to multiple threads sharing resource. Threadlocal solves the multi-threaded concurrent access from another perspective. Threadlocal maintains a copy of the variable bound to each thread, thereby isolating multiple thread data, each thread has its own variable copy Therefore, it is not necessary to synchronize the variable. ThreadLocal provides a thread secure shared object that can encapsulate unsafe's entire variable into Threadlocal when writing multi-threaded code, or encapsulates the thread-specific state of the object into Threadlocal.

Since ThreadLocal can hold any type of object, the value of the current thread using the Threadlocal GET is required to make mandatory type conversion. But as the new Java version (1.5) introduces the template, the new support template parameter will benefit from it. It is also possible to reduce the mandatory type conversion, and some error checks will be used to compile period, and the use of Threadlocal will be simplified to a certain extent.

to sum up

转载请注明原文地址:https://www.9cbs.com/read-119743.html

New Post(0)