有时候,执行PostgreSQL查询时出错:
Caused by: org.postgresql.util.PSQLException: ERROR: deadlock detected
Detail: Process 6805 waits for ShareLock on transaction 1985349; blocked by process 30535.
Process 30535 waits for ShareLock on transaction 1985351; blocked by process 6805.
Hint: See server log for query details.
Where: while inserting index tuple (19357,14) in relation "item_itemid_itemversion_ukey"
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270) [postgresql-9.1-901-1.jdbc4.jar:]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998) [postgresql-9.1-901-1.jdbc4.jar:]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255) [postgresql-9.1-901-1.jdbc4.jar:]
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570) [postgresql-9.1-901-1.jdbc4.jar:]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420) [postgresql-9.1-901-1.jdbc4.jar:]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:366) [postgresql-9.1-901-1.jdbc4.jar:]
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) [hibernate-core-4.2.22.Final-redhat-1.jar:4.2.22.Final-redhat-1]
... 99 more
错误的原因可能是什么?
修改
从日志文件中获取更多信息:
2018-06-29 11:16:10 UTC:10.120.40.41(54058):iwidgetarchive@iwidgetarchive_migration:[28533]:ERROR: deadlock detected
2018-06-29 11:16:10 UTC:10.120.40.41(54058):iwidgetarchive@iwidgetarchive_migration:[28533]:DETAIL: Process 28533 waits for ShareLock on transaction 1997995; blocked by process 12716.
Process 12716 waits for ShareLock on transaction 1997994; blocked by process 28533.
Process 28533: insert into item (description, itemid, itemversion, title, id) values ($1, $2, $3, $4, $5)
Process 12716: insert into item (description, itemid, itemversion, title, id) values ($1, $2, $3, $4, $5)
2018-06-29 11:16:10 UTC:10.120.40.41(54058):iwidgetarchive@iwidgetarchive_migration:[28533]:HINT: See server log for query details.
2018-06-29 11:16:10 UTC:10.120.40.41(54058):iwidgetarchive@iwidgetarchive_migration:[28533]:CONTEXT: while inserting index tuple (30446,16) in relation "item_itemid_itemversion_ukey"
2018-06-29 11:16:10 UTC:10.120.40.41(54058):iwidgetarchive@iwidgetarchive_migration:[28533]:STATEMENT: insert into item (description, itemid, itemversion, title, id) values ($1, $2, $3, $4, $5)
两个不同的Java线程试图同时在同一表中插入值。
问题是如何避免数据库中的并发插入死锁。 DB:Postgres 9.6