我在写一个servlet,通过访问和修改数据库中的某些表来处理每个请求。我希望与数据库的连接是线程安全的。我不想使用已有的库/框架(spring,hibernate等)。Java线程安全数据库连接
我知道我可以通过以下方式使用Java的ThreadLocal的这个:
public class DatabaseRegistry { //assume it's a singleton
private Properties prop = new Properties();
public static final ThreadLocal<Connection> threadConnection = new ThreadLocal<Connection>();
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类?还是有更好的方法来做到这一点,使所有连接线程安全?
谢谢
http://stackoverflow.com/questions/1209693/is-mysql-connector-jdbc-thread-safe – 2012-02-25 16:11:43
我认为这不是一个好的做法。请使用连接池,它将保留可用连接的核心大小。如果你使用ThreadLocal,每个请求都将是自己的一个连接,如果你的web服务器是阻塞的,连接将不会按时发布。 – 2015-03-20 02:26:17