Spring MVC multithreading concurrency

Source: Internet
Author: User

Threadlocal provides a new way to solve the concurrency problem of multi-thread. Using this tool class, you can write beautiful multithreaded programs very concisely.

Http://www.xuebuyuan.com/1628190.html

We know that spring has reduced the difficulty of developers using a variety of data persistence techniques through various DAO template classes. These template classes are thread-safe, meaning that multiple DAO can reuse the same template instance without conflicts.
We use the template class to access the underlying data, and depending on the persistence technology, the template class needs to bind the resources of the data connection or session. However, these resources are inherently non-thread-safe, meaning that they cannot be shared by multiple threads at the same time.
Although the template class obtains a data connection or session through a resource pool, the resource pool itself addresses the caching of data connections or sessions and is not a thread-safe issue for data connections or sessions.
In the traditional experience, if an object is non-thread-safe, access to the object must be thread-synchronized with synchronized in a multithreaded environment. However, spring's DAO template class does not adopt the thread synchronization mechanism because thread synchronization restricts concurrent access, which can result in a significant performance penalty.
In addition, resolving performance security issues through code synchronization can be challenging and may enhance several times the implementation difficulty. What kind of magic is the template class, can you solve the problem of thread safety without synchronizing? The answer is threadlocal!.
Threadlocal play an important role in spring, in the management of the request scope of the bean, transaction management, task scheduling, AOP and other modules have appeared their figure, play a pivotal role. To understand the underlying technology of spring transaction management, Threadlocal is the fortress of the hill that must be conquered.
What is threadlocal?
As early as in the version of JDK1.2, the java.lang.threadlocal,threadlocal provides a new idea for solving the concurrency problem of multi-thread. 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 Xlfortran) 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 ()
The value of the current thread local variable is removed to reduce memory usage, which is a new method of JDK5.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.
Protected Object 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, with the new version of the API methods Voidset (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
Class Simplethreadlocal {
Private Mapvaluemap = Collections.synchronizedmap (New HashMap ());
Public Voidset (Object newvalue) {
Valuemap.put (Thread.CurrentThread (), newvalue),//① key is a thread object, and the value is a copy of the variable for this thread
}
Publicobject get () {
Thread CurrentThread = Thread.CurrentThread ();
Object o = valuemap.get (currentthread);//② returns the variable corresponding to this thread
if (o = = null &&!valuemap.containskey (CurrentThread)) {//③ If not present in map, drop to map
Saved in.
o = InitialValue ();
Valuemap.put (CurrentThread, O);
}
return o;
}
Public Voidremove () {
Valuemap.remove (Thread.CurrentThread ());
}
Publicobject 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
Package Threadlocaldemo;
public class SequenceNumber {
① Specifies the initial value by overwriting the Threadlocal InitialValue () method with an anonymous inner class
Privatestatic threadlocal<integer> seqNum =new threadlocal<integer> () {
Public Integer InitialValue () {
return 0;
}
};
② getting the next sequence value
Public Intgetnextnum () {
Seqnum.set (Seqnum.get () + 1);
return Seqnum.get ();
}
publicstatic void Main (string[] args)
{
SequenceNumber sn = new SequenceNumber ();
③ 3 threads sharing sn, each generating serial number
testclient T1 = new TestClient (SN);
TestClient t2 = new TestClient (SN);
testclient t3 = new TestClient (SN);
T1.start ();
T2.start ();
T3.start ();
}
Privatestatic 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 sequence values per thread
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 JDK5.0 solves this problem through generics, simplifying the use of threadlocal to some extent, and listing 9 2 uses the new threadlocal<t> version of JDK5.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
public class Topicdao {
Private Connection Conn;① A non-thread-safe variable
public void Addtopic () {
Statement stat = conn.createstatement (); ② reference non-thread-safe variable
...
}
}

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
Package Threadlocaldemo;
Import java.sql.Connection;
Import java.sql.SQLException;
Import java.sql.Statement;
public class SqlConnection {
① Saving connection variables using threadlocal
Privatestatic threadlocal<connection>connthreadlocal = newthreadlocal<connection> ();
Publicstatic Connection getconnection () {
② If Connthreadlocal does not have a connection corresponding to this thread to create a new connection,
and save it in a thread-local variable.
if (connthreadlocal.get () = = null) {
Connection conn = getconnection ();
Connthreadlocal.set (conn);
Return conn;
} else {
return Connthreadlocal.get ();
③ directly returns thread-local variables
}
}
Public Voidaddtopic () {
④ get thread-corresponding connection from threadlocal
try {
Statement stat = getconnection (). createstatement ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
}

Spring MVC multithreading concurrency

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.