Java Summary series: Java Multithreading (four)

Source: Internet
Author: User

What is threadlocal?

As early as the version of JDK 1.2, Java.lang.threadlocal,threadlocal provides a new way to solve the concurrency problem of multi-threaded threads. Using this tool class, you can write beautiful multithreaded programs very concisely.

Threadlocal is easy to words too literally, assuming it is a "local thread". In fact, threadlocal is not a thread, but a local variable of thread, perhaps naming it as threadlocalvariable is easier to understand.

When you use threadlocal to maintain variables, Threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy without affecting the copy of the other thread.

From the thread's point of view, the target variable is like a thread's local variable, which is the meaning of the "local" in the class name.

Thread-local variables are not a new Java invention, and many languages (such as IBM IBM XL FORTRAN) provide thread-local variables at the syntactic level. There is no language-level support in Java, but rather a disguised way to provide support through the Threadlocal class.

Therefore, the code to write thread-local variables in Java is relatively clumsy, resulting in thread-local variables not being well-popularized in Java developers.

interface method for Threadlocal

Threadlocal class interface is very simple, there are only 4 methods, let us first look at:

void set (Object value)

Sets the value of the thread local variable for the current thread.

Public Object Get ()

This method returns the thread local variable that corresponds to the current thread.

public void Remove ()

Removes the value of the current thread local variable to reduce memory usage, which is a new method of JDK 5.0. It is important to note that when the thread ends, the local variables of the thread that should be used are automatically garbage collected, so it is not necessary to explicitly call the method to clear the thread's local variables, but it can speed up the memory reclamation.

1 protectedObject initialValue()

Returns the initial value of the thread's local variable, which is a protected method, apparently designed for subclasses to overwrite. This method is a deferred call method that executes only when the thread calls get () or set (Object) for the 1th time, and executes only 1 times. The default implementation in Threadlocal returns a null directly.

It is worth mentioning that, in JDK5.0, Threadlocal already supports generics, and the class name of the class has become threadlocal<t>. The API methods are also adjusted accordingly, and the new version of the API method is void set (t value), t get (), and T InitialValue ().

How does threadlocal maintain a copy of a variable for each thread? The idea is simple: there is a map in the Threadlocal class that stores a copy of the variable for each thread, the key for the element in the map is the thread object, and the value corresponds to the variable copy of the thread. We can provide a simple implementation version by ourselves:

Code Listing 1 Simplethreadlocal

123456789101112131415161718192021 public class SimpleThreadLocal { private Map valueMap = Collections.synchronizedMap(new HashMap()); public void set(Object newValue) { valueMap.put(Thread.currentThread(), newValue);//①键为线程对象,值为本线程的变量副本 } public Object get() { Thread currentThread = Thread.currentThread(); Object o = valueMap.get(currentThread);//②返回本线程对应的变量 if (o == null && !valueMap.containsKey(currentThread)) {//③如果在Map中不存在,放到Map中保存起来。 o = initialValue(); valueMap.put(currentThread, o); } return o; } public void remove() { valueMap.remove(Thread.currentThread()); } public Object initialValue() { return null; } }

Although the code listing 9?3 this threadlocal implementation version seems naïve, it is similar to the Threadlocal class provided by the JDK in the implementation.

A theadlocal instance

Below, we have a specific example to understand the specific use of threadlocal.

Code Listing 2 SequenceNumber

123456789101112131415161718192021222324252627282930313233343536373839 package com.baobaotao.basic; public class SequenceNumber { //①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值 private static ThreadLocal seqNum = new ThreadLocal(){ public Integer initialValue(){ return 0; } }; //②获取下一个序列值 public int getNextNum(){ seqNum.set(seqNum.get()+1); return seqNum.get(); } public static void main(String[] args) { SequenceNumber sn = new SequenceNumber(); //③ 3个线程共享sn,各自产生序列号 TestClient t1 = new TestClient(sn); TestClient t2 = new TestClient(sn); TestClient t3 = new TestClient(sn); t1.start(); t2.start(); t3.start(); } private static class TestClient extends Thread { private SequenceNumber sn; public TestClient(SequenceNumber sn) { this.sn = sn; } public void run() { for (int i = 0; i < 3; i++) {//④每个线程打出3个序列值 System.out.println("thread["+Thread.currentThread().getName()+ "] sn["+sn.getNextNum()+"]"); } } } }

In general, we define the subclass of threadlocal by means of an anonymous inner class, providing the initial variable value, as shown in the example ①. TestClient threads produce a set of serial numbers, and at ③ we generate 3 testclient that share the same SequenceNumber instance. Run the above code and output the following results on the console:

Thread[thread-2] sn[1]

THREAD[THREAD-0] sn[1]

THREAD[THREAD-1] sn[1]

Thread[thread-2] sn[2]

THREAD[THREAD-0] sn[2]

THREAD[THREAD-1] sn[2]

Thread[thread-2] sn[3]

THREAD[THREAD-0] sn[3]

THREAD[THREAD-1] sn[3]

Examining the results of the output, we find that each thread produces a sequence number that shares the same SequenceNumber instance, but they do not interfere with each other, but instead produce separate serial numbers. This is because we provide a separate copy of each thread through threadlocal.

Comparison of thread synchronization mechanisms

What are the advantages of threadlocal compared to the thread synchronization mechanism? Both the threadlocal and thread synchronization mechanisms are designed to address the access violation of the same variable in multiple threads.

In the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult.

Threadlocal, however, solves multiple threads of concurrent access from another angle. Threadlocal provides a separate copy of the variable for each thread, isolating the access violation of multiple threads to the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code.

Because the threadlocal can hold any type of object, the Get () provided by the lower version of the JDK returns an object, which requires a type cast. But JDK 5.0 solves this problem with generics, and simplifies the use of threadlocal to some extent, and listing 9 2 uses the new threadlocal<t> version of JDK 5.0.

To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts the way of "changing time by Space". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

Spring uses threadlocal to resolve thread safety issues

We know that in general, only stateless beans can be shared in a multithreaded environment, and in spring, most beans can be declared as singleton scopes. is because spring is for some beans (such as Requestcontextholder, Transactionsynchronizationmanager, Localecontextholder, etc.) the non-thread-safe state is handled by threadlocal, making them also a thread-safe state, because stateful beans can be shared across multiple threads.

The general Web application divides into the presentation layer, the service layer and the persistence layer three levels, writes the corresponding logic in the different layers, the lower layer through the interface to the upper layer open function calls. In general, all program calls from receiving requests to returning responses belong to one thread, as shown in 9?2:

Figure 1 The same thread through three layers

This allows you to store some non-thread-safe variables in threadlocal as needed, and all associated objects are referenced to the same variable in the calling thread of the same request response.

The following example can reflect spring's transformation of the stateful bean:

Code Listing 3 Topicdao: non-thread safe

1234567 public class topicdao { &NBSP; Private connection Conn; //① a non-thread-safe variable &NBSP; public void addtopic () { &NBSP; Statement stat = conn.createstatement (); //② referencing non-thread-safe variables &NBSP; ... &NBSP; &NBSP; }

Because the conn at ① is a member variable, because the Addtopic () method is non-thread-safe, a new Topicdao instance (not singleton) must be created when it is used. The following uses Threadlocal to transform Conn, a non-thread-safe "state":

Code Listing 4 Topicdao: Thread safety

123456789101112131415161718192021 import java.sql.Connection; import java.sql.Statement; public class TopicDao { //①使用ThreadLocal保存Connection变量 private static ThreadLocal connThreadLocal = new ThreadLocal(); public static Connection getConnection(){ //②如果connThreadLocal没有本线程对应的Connection创建一个新的Connection, //并将其保存到线程本地变量中。 if (connThreadLocal.get() == null) { Connection conn = ConnectionManager.getConnection(); connThreadLocal.set(conn); return conn; }else{ return connThreadLocal.get();//③直接返回线程本地变量 } } public void addTopic() { //④从ThreadLocal中获取线程对应的Connection Statement stat = getConnection().createStatement(); } }

When using Topicdao, different threads first determine if Connthreadlocal.get () is null, or NULL, indicating that the current thread does not have a corresponding connection object. At this point, a connection object is created and added to the local thread variable, and if it is not NULL, the current thread already has the connection object, which can be used directly. This ensures that different threads use thread-related connection and do not use the connection of other threads. Therefore, this topicdao can be done singleton share.

Of course, this example itself is very rough, put connection threadlocal directly in DAO can only do this DAO's multiple methods share connection without thread safety problem, but can not be shared with other DAO the same connection, To do the same transaction multiple DAO shares the same connection, you must use Threadlocal to save the connection in a common external class.

Summary

Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency.

Java Summary series: Java Multithreading (four)

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.