Enum中的getConnection()应该同步吗?
哪一个是线程安全的?
首先:
public enum DBConnection {
POSTGRESQL("jdbc:postgresql://localhost:5432/mydb", "vagrant", "vagrant"),
MYSQL("jdbc:mysql://localhost:3306/mydb", "vagrant", "vagrant");
DBConnection(String host, String user, String password) {
this.host = host;
this.user = user;
this.password = password;
}
private final String host;
private final String user;
private final String password;
private Connection connection;
public Connection getConnection() throws SQLException {
if (connection == null || connection.isClosed()) {
connection = DriverManager.getConnection(host, user, password);
}
return connection;
}}
或第二,同步调用和volatile变量:
private volatile Connection connection;
public synchronized Connection getConnection() throws SQLException {
if (connection == null || connection.isClosed()) {
connection = DriverManager.getConnection(host, user, password);
}
return connection;
}
调用连接,例如:
try (Connection connection = DBConnection.POSTGRESQL.getConnection()) {
// Prepared statement etc
}
} catch (SQLException ignored) {}
答案 0 :(得分:2)
哪一个是线程安全的?
第一个选项不是线程安全的,因为您有 check-then-act 情况,可能导致竞争条件。第二个选项是线程安全,但如果要同步整个volatile
方法,则使用getConnection
是多余的。
也就是说,最好使用连接池而不是 Singleton 数据库连接。