gao6rich 最近的时间轴更新
gao6rich

gao6rich

V2EX 第 487796 号会员,加入于 2020-05-05 13:54:40 +08:00
gao6rich 最近回复了
277 天前
回复了 ffyyhh 创建的主题 MacBook 买 macbook air 好还是 pro 好
内存大的 air 吧
2022-12-12 19:17:59 +08:00
回复了 gao6rich 创建的主题 Java ThreadLocal
class ConnectionManager {
private Connection connect = null;

public Connection openConnection() {
if (connect == null) {
connect = DriverManager.getConnection();
}
return connect;
}

public void closeConnection() {
if (connect != null)
connect.close();
}
}

class Dao {
public void insert() {
ConnectionManager connectionManager = new ConnectionManager();
Connection connection = connectionManager.openConnection();

// 使用 connection 进行操作

connectionManager.closeConnection();
}
}
===========================================使用 ThreadLocal

public class ConnectionManager {

private static final ThreadLocal<Connection> dbConnectionLocal = new ThreadLocal<Connection>() {
@Override
protected Connection initialValue() {
try {
return DriverManager.getConnection("", "", "");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
};

public Connection getConnection() {
return dbConnectionLocal.get();
}
}
===========================================不使用 ThreadLocal

这两者有什么区别呢
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2745 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 13ms · UTC 11:44 · PVG 19:44 · LAX 03:44 · JFK 06:44
Developed with CodeLauncher
♥ Do have faith in what you're doing.