1
我目前使用的池连接(光速)和抽象工厂模式在Java中实现我的MySQL查询像这样:抽象工厂模式和HikariCP
MySqlFactoryDAO.java
public class MySqlFactoryDAO extends FactoryDAO {
private static HikariDataSource connPool_;
public static Connection createConnection() throws SQLException {
if (connPool_ == null) {
// Load database configuration
PropertiesFile props = FactoryConfig.getConfig().getDatabaseProperties();
connPool_ = new HikariDataSource();
connPool_.setJdbcUrl(props.getString(Params.DB_URL,""));
connPool_.setUsername(props.getString(Params.DB_USER,"root"));
connPool_.setPassword(props.getString(Params.DB_PASSWORD,"root"));
}
return connPool_.getConnection();
}
//-------------------------------------------------------------------------
public ProductDAO getProductDAO() {
return new ProductMySQLFactoryDAO();
}
}
ProductMySQLFactoryDAO。 java的
public class ProductMySQLFactoryDAO implements ProductDAO {
public int insertProduct(String name) {
...
Connection conn = MySqlFactoryDAO.createConnection();
...
}
}
我在想,如果这个代码是线程安全的,我认为有在coonPool_
初始化的时间的问题。我在维基百科上阅读过类似“Initialization-on-demand_holder_idiom”的内容,但我不确定。有没有人有更好的实施这个解决这个问题或只是一个更好的新的?
是的,它应该是私人的,我把它复制错了。我想过一种同步方法,但它认为在这里同步会降低性能。 – amarincolas