插入钩子后如何避免并发问题(死锁)?

时间:2019-07-05 05:00:00

标签: grails concurrency deadlock grails-2.2

当两个请求同时调用afterinsert方法时,将引发此错误

ERROR 2019-07-03 11:59:18,152 [ajp-bio-8109-exec-34040] util.JDBCExceptionReporter: Deadlock found when trying to get lock; try restarting transaction
ERROR 2019-07-03 11:59:18,152 [ajp-bio-8109-exec-34037] util.JDBCExceptionReporter: Cannot add or update a child row: a foreign key constraint fails (`rcroadweb`.`inventory_entry_order`, CONSTRAINT `FKDD86A2DE546E2B52` FOREIGN KEY (`order_id`) REFERENCES `inventory_order` (`id`))
ERROR 2019-07-03 11:59:18,173 [ajp-bio-8109-exec-34037] events.PatchedDefaultFlushEventListener: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at invoice.InventoryEntry$_afterInsert_closure1.doCall(InventoryEntry.groovy:105)
    at invoice.InventoryEntry.afterInsert(InventoryEntry.groovy:101)
    at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:46)
    at registration.RegistrationService$_createInvoices_closure11.doCall(RegistrationService.groovy:414)
    at registration.RegistrationService.createInvoices(RegistrationService.groovy:316)
    at registration.RegistrationService$_completeSale_closure14.doCall(RegistrationService.groovy:653)
    at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:686)
插入钩子之后的

InventoryEntry域类如下所示。错误是在这一点上。

void afterInsert(){
        if (this.metaClass.hasMetaProperty('unsavedOrders')){
            withNewSession{ session ->
                this.unsavedOrders.each{ order ->
                    InventoryEntryOrder.create(this, order)
                }
                session.flush()
            }
            this.unsavedOrders.clear()
        }
    }

我在处理并发问题方面经验不足,因此感谢专家的任何帮助。我的直觉是使用锁,以便一次只有1个线程进入此方法。感谢您的见解!

0 个答案:

没有答案