我正在使用Hibernate 4.2.21,在几篇文章中我看到有些人在方法中使用Synchronized来创建Hibernate的Session Factory,我的问题是关于什么是最佳实践,有或没有?从我的角度来看,我认为如果我们将变量定义为静态,则同步没有意义..
public class HibernateSessionFactory {
private static SessionFactory sessionFactory = buildSessionFactory();
private static final Logger logger = LogManager.getLogger(HibernateSessionFactory.class);
private HibernateSessionFactory() {}
private static synchronized SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration();
SessionFactory sf = null;
try {
configuration.configure("hibernate.cfg.xml");
configuration.setProperty("hibernate.dialect", System.getProperty("myApp.db.dialect"));
configuration.setProperty("hibernate.connection.driver_class", System.getProperty("myApp.db.driver"));
configuration.setProperty("hibernate.connection.datasource", System.getProperty("myApp.db.jndi"));
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
}
return sf;
} catch (HibernateException ex) {
logger.error("Init SessionFactory creation failed: ", ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdownSessionFactory() {
if(!sessionFactory.isClosed()){
sessionFactory.close();
logger.info("Session Factory shutdown");
}else{
logger.info("Session Factory is already closed");
}
}
}