spring框架的事务管理中使用threadlocal来管理连接,每个线程是单独的连接,当事务失败时不能影响到其他线程的事务过程或结果,还有大家耳闻目睹的orm框架、mybatis也是用threadlocal管理,sqlsession也是如此。
//spring transactionsynchronizationmanager类@overrideprotected void dobegin(object transaction, transactiondefinition definition) { datasourcetransactionobject txobject = (datasourcetransactionobject) transaction; connection con = null; try { //此处省略n行代码 if (txobject.isnewconnectionholder()) { //绑定数据库连接到线程中 transactionsynchronizationmanager.bindresource(obtaindatasource(), txobject.getconnectionholder()); } } catch (throwable ex) { if (txobject.isnewconnectionholder()) { //当发生异常时,移除线程中的连接 datasourceutils.releaseconnection(con, obtaindatasource()); txobject.setconnectionholder(null, false); } throw new cannotcreatetransactionexception(could not open jdbc connection for transaction, ex); }}
2、防止内存泄漏
通常我们是使用如下的方式操作threadlocal,在使用完threadlocal后一定要remove掉,防止内存泄露。
private static final threadlocal<loginuser> loginuserlocal = new threadlocal<loginuser>(); public static loginuser getloginuser() { return loginuserlocal.get();} public static void setloginuser(loginuser loginuser) { loginuserlocal.set(loginuser);} public static void clear() { loginuserlocal.remove();} //在使用完后一定要清理防止内存泄露try{ loginuserlocal.set(loginuser); //执行其他业务逻辑}finally{ loginuserlocal.remove();}
以上就是java中threadlocal怎么应用的详细内容。