关于多线程ThreadLocal应用

多线程应用是为加快访问速度、减少降级时间。请看代码:

public static final ThreadLocal<Map<String, Connection>> runtimeDBConn = new ThreadLocal<Map<String, Connection>>();

定义为当前线程中的数据库连接,既保证了数据库连接访问安全,也能够提高访问速度。

/*

  如下为获取当前线程中的数据库连接。

  所属类:

ssh. mfw. base. ejb.AbstractRunTimeProcessBean< E>

*/

protected Connection getConnection() throws Exception {
Map<String, Connection> connMap = insistonCommon.runtimeDBConn.get();//获取当前线程的共享变量
Connection conn = null;
if (connMap != null) {
conn = (Connection) connMap.get(getApplicationId());
System.out.println("Connection:"+conn.hashCode());//打印数据库连接的hashcode
}

if (conn == null || conn.isClosed()) {
conn = getDataSource().getConnection();
Map<String, Connection> map = new HashMap<String, Connection>();
map.put(getApplicationId(), conn);//把当前的数据连接与应用程序绑定。
insistonCommon.runtimeDBConn.set(map);//当前线程共享变量的值
if(conn.getMetaData().getDriverName().equals("jTDS Type 4 JDBC Driver for MS SQL Server and Sybase")){
conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
}
}


return MonProxyFactory.monitor(conn);
}

猜你喜欢

转载自blog.csdn.net/qq_17091393/article/details/80722402