hibernate异常LockAcquisitionException:无法更新

时间:2012-10-09 20:26:09

标签: java hibernate deadlock

在我的应用程序中,我使用的是Java,Hibernate(Annotations)和mySQL。 它在大多数情况下工作正常,但偶尔会发生这种错误:

SEVERE: Could not synchronize database state with session
org.hibernate.exception.LockAcquisitionException: could not update: [myPack.Analysis$TestRun#5191]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:107)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2596)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:180)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at myPack.Analysis.fileHelper(Analysis.java:977)
    at myPack.Analysis.dirHelper(Analysis.java:702)
    at myPack.Analysis.dirHelper(Analysis.java:714)
    at myPack.Analysis.dirHelper(Analysis.java:714)
    at myPack.Analysis.dirHelper(Analysis.java:714)
    at myPack.Analysis.dirHelper(Analysis.java:714)
    at myPack.Analysis.dirHelper(Analysis.java:711)
    at myPack.Analysis.parseLog(Analysis.java:682)
    at myPack.Analysis.main(Analysis.java:614)

Analysis.java中最可疑的一行是:

dbPerson = (Person) session.get(Person.class, dbPersonId, LockOptions.READ);

我所做的是使用dbPersonId获取行并根据需要更新/更改行内容。例如:

dbPerson.Name = "Jack";
dbPerson.Age ++;
session.saveOrUpdate(dbPerson);

我猜测LockOptionsNONE, UPGRADE的错误 我尝试使用不同的锁定选项,例如{{1}} ......但仍然没有运气。

最令人沮丧的是我甚至无法手动重现此错误。它只会在Analysis.java被多次调用时发生一次。

我知道会话不是线程安全的,但我不确定这是否与此相关。

任何想法都会受到赞赏,非常感谢!

1 个答案:

答案 0 :(得分:3)

由于它使用READ锁定选项,我捕获异常,让线程休眠一段时间,然后尝试再次获取锁定,这解决了问题:

try {
  dbPerson = (Person) session.get(Person.class, dbPersonId, LockOptions.READ);
} catch (RuntimeException e) {
  if (e instanceof LockAcquisitionException) {
    try {
      Thread.sleep(15000);
      dbPerson = (Person) session.get(Person.class, dbPersonId, LockOptions.READ);                      
     } else {
      throw e;
     }