Home > Java > javaTutorial > body text

How to apply ThreadLocal in java

PHPz
Release: 2023-05-04 13:01:06
forward
1493 people have browsed it

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);
    }
}
Copy after login

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

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template