【问题标题】:Hibernate multi thread and synchronization休眠多线程和同步
【发布时间】:2011-01-04 10:38:32
【问题描述】:

我有以下代码:

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
Configuration cfg = new Configuration();

cfg=cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
    System.out.println("** Initial SessionFactory creation failed: " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal hibernateSession = new ThreadLocal();

public static Session currentSession() {
    Session s = (Session) hibernateSession.get();
    if (s == null) {
        s = sessionFactory.openSession();
        //System.out.println("sessionFactory.openSession()");
        hibernateSession.set(s);
    }
    return s;
}

public static void closeSession() {
    Session s = (Session) hibernateSession.get();
    if (s != null)
        s.close();
    hibernateSession.set(null);
}
}

还有

public class Db {
    public static synchronized void Insert(Object updateBean) {
    org.hibernate.Session hibernateSession = HibernateUtil.currentSession();
    try {
        Transaction tx = hibernateSession.beginTransaction();
        hibernateSession.save(updateBean);
        tx.commit();
    } catch(Exception e) {
        System.out.println("*hibernate insert Exception: "+e.getMessage());
    }

    HibernateUtil.closeSession();
}
}

Hibernate 正在使用 c3p0 池化。 然后在繁忙的服务器生产环境中从 JSP 页面调用 Db.Insert。

我的问题是,如果我删除了 Db.Insert(Object) 上的“同步”,这会导致问题吗?

我意识到这是我很可能已经知道的事情,但不要也不想尝试它并得到错误。

另外,如果它可能导致上述问题,那么我不确定我是否理解使用 c3p0 进行连接池的意义......我目前的理解是调用 HibernateUtil.currentSession();或 hibernateSession.beginTransaction();从 c3p0 池中调用一个可用的连接,并且永远不会相遇。

抱歉,第一个代码没有显示“代码”,这个网络表单只是不想正常工作。

感谢阅读

【问题讨论】:

  • 我为您格式化了代码 - 下次请使用编辑器中的{} 按钮,或者简单地将您的代码缩进 4 个空格 :-)
  • 谢谢,彼得。我确实尝试了 {} 几次,但在第一段代码上仍然不是很好。

标签: hibernate


【解决方案1】:

如果您确实删除了synchronized,则不会有任何问题,实际上您的应用程序可能会执行得更好一些。

取决于您的休眠配置。 Hibernate 将在会话的生命周期或事务的生命周期内从池中请求连接。

【讨论】:

  • 我没想到,但知道需要问...谢谢 Gareth。
  • oop.. 另外.. 是的,原因是为了提高性能,尤其是在高峰期。
  • 但不要相信我的话,去yourkit.com 获取 YourKit profiler 的副本。先测量,再切割
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 2011-06-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多