我在寫一個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