"Java Project Combat" Threadlocal package connection, to achieve the same thread sharing resources

Source: Internet
Author: User

Thread safety has always been the program of the focus of the Apes, multithreading has been more annoying topic, presumably we have encountered various problems, I will no longer be tired. Of course, there are many solutions, this blog provides a good way to solve the problem of thread safety.

First of all, we have a simple understanding of threadlocal, followed by the example + analysis, the last sentence summed up.


1. Meet Threalocal


Knowing threadlocal must be through API documentation, not just persuasive, but it will give you a more comprehensive explanation. I'm going to take a picture of you from the API document and mark out the seven points that need to be understood, and the following example is the key explanation for the seven parts.




For the above content, do not understand does not matter, we through the following example to deepen the understanding, after the example I will give you a more in-depth explanation.


2, Threalocal package Connection example + analysis


The following code is just threalocal encapsulation connection core code, for redundant content to avoid success, and a part of the code is "dom4j parse XML file, connect the database" content, very suitable for beginners, if necessary, please move here.


Package com.bjpowernode.drp.util;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import java.sql.Statement; /** * Threadlocal Package Connection * * * * * * * * * * * * * * As long as the thread is active, no end, threadlocal is accessible, you can access this thread's connection * * @author Liang * * * Class ConnectionManager {//Use ThreadLocal to save Connection variable private static threadlocal<connection> Connectionholder
	
	= new Threadlocal<connection> (); /** * Connection Connection * @return/public static Connection getconnection () {//threadlocal Gets the Connection of the current thread Connec
		tion conn = Connectionholder.get ();
		If Threadlocal does not bind the corresponding connection, create a new connection,//and save it to the local thread variable.
				if (conn = = null) {try {jdbcconfig jdbcconfig = Xmlconfigreader.getinstance (). Getjdbcconfig ();				
				Class.forName (Jdbcconfig.getdrivername ());
				conn = Drivermanager.getconnection (Jdbcconfig.geturl (), Jdbcconfig.getusername (), Jdbcconfig.getpassword ());
	Sets the current thread's connection to threadlocal			Connectionholder.set (conn);
				catch (ClassNotFoundException e) {e.printstacktrace ();
			throw new ApplicationException ("System error, please contact system Administrator");
			catch (SQLException e) {e.printstacktrace ();
			throw new ApplicationException ("System error, please contact system Administrator");									
		
	} return conn; /** * Closes connection, clears connection/public static void CloseConnection () {//threadlocal in the collection to obtain the current thread's connection Co
		Nnection conn = Connectionholder.get ();
		Closes the connection when the current thread's connection is not empty.
				IF (conn!= null) {try{conn.close ();
			After the connection is closed, remove the connection Connectionholder.remove from the Threadlocal collection ();
			}catch (SQLException e) {e.printstacktrace (); } } } }


The following code shows you how threadlocal can share connection resources in the same thread.


Package Com.bjpowernode.drp.flowcard.manager.impl;
Import java.sql.Connection;
Import Java.util.Date;
Import Com.bjpowernode.drp.flowcard.dao.FlowCardDao;
Import Com.bjpowernode.drp.flowcard.domain.FlowCard;
Import Com.bjpowernode.drp.flowcard.manager.FlowCardManager;
Import com.bjpowernode.drp.util.ApplicationException;
Import Com.bjpowernode.drp.util.BeanFactory;
Import Com.bjpowernode.drp.util.ConnectionManager;
Import com.bjpowernode.drp.util.DaoException;

Import Com.bjpowernode.drp.util.PageModel;
	public class Flowcardmanagerimpl implements Flowcardmanager {private Flowcarddao Flowcarddao; Constructor public Flowcardmanagerimpl () {This.flowcarddao = (Flowcarddao) beanfactory.getinstance (). Getdaoobject (
	Flowcarddao.class);
		@Override public void Addflowcard (Flowcard flowcard) throws ApplicationException {Connection conn = null;
			try{//Get thread-corresponding connection conn from threadlocal = Connectionmanager.getconnection (); Start Transaction connectionmanager.begintransaction (Conn);
			Generate flow to String Flowcardvouno = Flowcarddao.generatevouno ();
			Add flow to single master information Flowcarddao.addflowcardmaster (Flowcardvouno, Flowcard);
			Add Flow Order Detail Information Flowcarddao.addflowcarddetail (Flowcardvouno, Flowcard.getflowcarddetaillist ());		
		Submit Transaction connectionmanager.committransaction (conn);
			}catch (daoexception e) {//ROLLBACK TRANSACTION connectionmanager.rollbacktransaction (conn); throw new ApplicationException ("Add flow slip failed.")
		");
		}finally{//Close the connection and clear connectionmanager.closeconnection () from the Threadlocal collection; }
	
	}
}

parsing:

1, this class provides a thread-local variable, which is independent of the initialization copy of the variable

You may not understand local variables, why not member variables or global variables, the scope of the variables involved in this case. Threadlocal has a larger scope than local variables, where resources can be shared and threads are safe.

We also learned that threadlocal is not a local thread, but rather a thread variable that is only used to maintain local variables. For each thread to provide their own version of the variant to avoid multithreading conflicts, each thread only need to maintain their own version of the good, independent of each other, will not affect each other.

2, each thread has its own one threadlocal, modify it does not affect other threads

As we can see from the following diagram, saving something into a threadlocal creates a map, a thread corresponds to a map collection, and then threadlocal hangs the map under the current thread, a key value corresponding to a value, So the map belongs to the current thread only. (If you don't understand the characteristics of a map you can poke it)




3. After the thread disappears, all copies of its threaded local instance are garbage collected (unless there are other references to those replicas).

Above we know that the variable copy of the stored in the map, when we do not call set, at this time does not point the reference to the ' map ', and this thread exit will perform a resource reclamation operations, the requested resources are reclaimed, in fact, is to set the reference to NULL. No reference is made to the map at this time and is garbage collected.


3, contrast threadlocal and synchronized synchronization mechanism


Same point:

1, threadlocal and thread synchronization mechanism can solve the access conflict problem of the same variable in multiple threads. different points:

1, the application of different circumstances

In the synchronization mechanism, use synchronization to ensure that only one thread accesses at the same time, and cannot access shared resources at once, otherwise there is an error. Threadlocal isolates the associated resources and can share the resource in the same thread. Independent of each other, the modification will not affect the other.

2, the effect of the final implementation is different

For multithreading resource sharing problem, the synchronization mechanism adopts the way of " Time changing Space ", and Threadlocal adopts the way of " changing time in Space ". The former provides only one variable, allowing different threads to be queued for access, and the latter provides a variable for each thread so that it can be accessed simultaneously without affecting each other.

The above blog link is also a thread synchronization mechanism synchronized example, we can experience their similarities and differences through two examples, plus the similarities and differences of the analysis, I believe you have a very deep understanding of them.


4, a sentence summary threadlocal


Threadlocal is a good way to solve thread-safety problems, and in many cases, threadlocal is simpler, more convenient, and more concurrency-efficient than using the synchronized synchronization mechanism to solve thread-safety problems.



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.