gao6rich's recent timeline updates
gao6rich

gao6rich

V2EX member #487796, joined on 2020-05-05 13:54:40 +08:00
gao6rich's recent replies
Feb 5, 2024
Replied to a topic by ffyyhh MacBook 买 macbook air 好还是 pro 好
内存大的 air 吧
Dec 12, 2022
Replied to a topic by 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

这两者有什么区别呢
About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2493 Online   Highest 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 20ms · UTC 12:19 · PVG 20:19 · LAX 05:19 · JFK 08:19
♥ Do have faith in what you're doing.