13

在我的应用程序中,我使用 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);

我猜有什么问题,LockOptions我尝试使用不同的锁定选项,例如NONE, UPGRADE......但仍然没有运气。

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

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

任何想法将不胜感激,非常感谢!

4

1 回答 1

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;
     }
于 2012-10-24T21:39:03.763 回答