mercredi 24 février 2016

Abstract factory pattern and HikariCP

I'm currently using a pool connection(Hikari) and an abstract factory pattern to implement my MySQL queries in Java like this:

MySqlFactoryDAO.java

public class MySqlFactoryDAO extends FactoryDAO {

   public 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();
      ...
   }    
}

I was wondering if this code is thread safe and I think that there is a problem at the time of initialization of coonPool_. I have read things like "Initialization-on-demand_holder_idiom" in wikipedia but I am not sure about it. Does anyone have a better implementation of this to solve this problem or just a better new one?

Aucun commentaire:

Enregistrer un commentaire