Home  >  Article  >  Java  >  How to apply ThreadLocal in java

How to apply ThreadLocal in java

PHPz
PHPzforward
2023-05-04 13:01:061459browse

1. Applications in various frameworks

#ThreadLocal is used in transaction management of Spring framework to manage connections, and each thread is separate Connection, when a transaction fails, it cannot affect the transaction process or results of other threads. The ORM framework and Mybatis that everyone has heard about are also managed by ThreadLocal, as is SqlSession.

//Spring TransactionSynchronizationManager类
@Override
protected 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. Prevent memory leaks

Usually we use the following method to operate ThreadLocal. After using threadlocal, we must remove it to prevent memory leaks. .

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();
}

The above is the detailed content of How to apply ThreadLocal in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete