我正在编写一个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类?还是有一种更好的方法来使所有连接线程安全?
谢谢