【发布时间】:2021-10-29 07:41:23
【问题描述】:
我正在努力将使用单个Session 实例变量的代码库转换为线程安全环境,该变量最初是使用getCurrentSession() 获得的,用于所有数据库通信。我理解为什么这是一个线程安全的风险。为了使代码库线程安全,我删除了实例变量,并为每个“工作单元”打开和关闭了一个会话。示例:
private void updateEntity(DataEntity dataEntity)
{
Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.beginTransaction();
try
{
session.update(dataEntity);
transaction.commit();
}
catch (RuntimeException e)
{
transaction.rollback();
}
finally
{
session.close();
}
}
我的理解是getCurrentSession()获取的一个session在事务提交后会自动关闭。我也通过调试证明了这一点。这是使用getCurrentSession() 的正确方法吗?这个线程安全吗?
【问题讨论】: