java mysql 线程安全_Java线程安全数据库连接

我正在编写一个Servlet,通过访问和修改数据库中的某些表来处理每个请求.我希望与数据库的连接是线程安全的.我不想为此使用已经存在的库/框架(spring,hibernate等).

我知道我可以通过以下方式为此使用java的ThreadLocal:

public class DatabaseRegistry { //assume it's a singleton

private Properties prop = new Properties();

public static final ThreadLocal threadConnection = new ThreadLocal();

private Connection connect() throws SQLException {

try {

// This will load the MySQL driver, each DB has its own driver

Class.forName("com.mysql.jdbc.Driver");

// Setup the connection with the DB

Connection connection = DriverManager

.getConnection("jdbc:mysql://" + prop.getProperty("hostname") + "/" + prop.getProperty("database") + "?"

+ "user=" + prop.getProperty("username") + "&password=" + prop.getProperty("password"));

return connection;

} catch (SQLException e) {

throw e;

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

return null;

}

public Connection getConnection() throws SQLException {

if(threadConnection.get() == null) {

Connection connection = connect();

threadConnection.set(connection);

return threadConnection.get();

} else

return threadConnection.get();

}

private void freeConnection(Connection connection) throws SQLException {

connection.close();

threadConnection.remove();

}

}

每次调用getConnection()时,新连接都会添加到ThreadLocal对象,然后在释放连接时将其删除.

这是这样做的正确方法,还是DatabaseRegistry本身应该扩展ThreadLocal类?还是有一种更好的方法来使所有连接线程安全?

谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值