ThreadLocal (thread-local variables)

First, the use of control transaction to complete business functions

      (1) ThreadLocal Introduction
      (2) ThreadLocal objects and methods
      (3) TestThreadLocal

Second, the test connector in obtaining two single-threaded connection

      (1) Test at JdbcUtil package
      (2) under test JdbcUtil2 package
      (3) given in the code package JdbcUtil2


First, the use of control transaction to complete business functions

(1) ThreadLocal Introduction
  • ThreadLocal function: to hold the same value for the same thread, hold different values ​​for different threads.
  • Objective: In each piece of code in a thread, only one connection is connected

Want to get in a single-threaded programming connection, it should be to get a connection with, but before the hand tools JDBC package , there is no use ThreadLocal control transaction, each will create a new connection, so consumption is very large. ThreadLocal a good solution to this problem.

(2) ThreadLocal objects and methods

Create a ThreadLocal objects:ThreadLocal<T> tdl = new ThreadLocal<T>();

ThreadLocal Methods:

  • set (T t); // Thread t is added to the current object.
  • get (); // get the object of the current Thread.
  • remove (); // remove the object in the current Thread.
(3)TestThreadLocal
package jdbc;

public class TestThreadLocal {
	public static void main(String[] args) throws Exception {
		//tl对象可以为同一个线程保存相同的值,为不同线程保存不同的值.
		final ThreadLocal<String> tl = new ThreadLocal<String>();
		Thread t1 = new Thread() {
			public void run() {
				tl.set("hello");
				System.out.println("t1:" + tl.get());
			}
		};
		t1.start();
		Thread.sleep(1000);
		
		Thread t2 = new Thread() {
			public void run() {
				tl.set("world");
				System.out.println("t2:"+tl.get());
			}
		};
		t2.start();
	}
}

Here Insert Picture Description

Second, the test connector in obtaining two single-threaded connection

(1) Test packet at JdbcUtil

Here Insert Picture Description
Here Insert Picture Description
Conn found two different addresses, the instructions for creating the two connections.

(2) Test packet at JdbcUtil2

Here Insert Picture Description
Here Insert Picture Description
This can be seen with a conn objects, the task is completed.

(3) given in the code package JdbcUtil2
package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Jdbc工具类
 * 1:properties配置文件 封装获取连接 释放资源 提高代码复用性√
 * 2:类加载时加载驱动√
 * 3:ThreadLocal控制事务√
 * 4:连接池,提高资源利用率×
 * 5:rowmapper封装 减少代码冗余×
 * 6:template封装 减少dao层代码冗余×
 * @author 郭乾亮1998
 *
 */
public class JdbcUtil2 {
	//创建properties
	static Properties pro = new Properties();
	//创建ThreadLocal<Connection>,可以为同一个线程保存同一个连接,为不同线程保存不同的连接
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	//加载驱动
	static{
		InputStream is = null;
		try {
			is = JdbcUtil.class.getResourceAsStream("/conf/db.properties");
			//加载文件
			pro.load(is);
			Class.forName(pro.getProperty("driverClassName"));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	//获取连接
	public static Connection getConnection() throws Exception{
		Connection conn = tl.get();//获得当前线程中的连接
		if(conn == null){//如果当前线程中没有连接
			String url = pro.getProperty("url");
			String user = pro.getProperty("username");
			String password = pro.getProperty("password");
			//创建连接
			conn = DriverManager.getConnection(url,user,password);
			//将连接保存到当前线程
			tl.set(conn);
		}
		return conn;
	}
	//释放资源
	public static void release(ResultSet rs,PreparedStatement pstm,Connection conn) throws Exception{
		if(rs!=null){
			rs.close();
		}
		if(pstm!=null){
			pstm.close();
		}
		if(conn!=null){
			conn.close();
			tl.remove();//将连接从当前线程中移除
		}
	}
}
Published 328 original articles · won praise 798 · views 110 000 +

Guess you like

Origin blog.csdn.net/weixin_43691058/article/details/103338727