Sco*_*ott 5 java postgresql deadlock jdbc
我正在尝试将一些文件插入到Postgres数据库中.由于需要大量复制,我们将文件本身放入file表中,然后将它们链接到我们与output_file表一起使用的数据库部分.由于file表也由除output_file(例如,类似input_file表)之外的表引用,其列之一是引用计数,当插入行时由触发器更新output_file(而其他表也是如此,尽管它们不是在问题发生的时候使用.
CREATE TABLE file
(
file_id serial PRIMARY KEY,
--other columns
occurences integer NOT NULL DEFAULT 0
);
CREATE TABLE output_file
(
output_file_id serial PRIMARY KEY,
--other columns
file_id integer REFERENCES file NOT NULL
);
CREATE OR REPLACE FUNCTION file_insert() RETURNS opaque AS '
BEGIN
UPDATE file
SET occurences = occurences + 1
WHERE file.file_id = NEW.file_id;
RETURN NEW;
END;
' LANGUAGE plpgsql;
CREATE TRIGGER output_file_insert AFTER INSERT
ON output_file FOR EACH ROW
EXECUTE PROCEDURE file_insert();
Run Code Online (Sandbox Code Playgroud)
插入文件的代码如下所示,并且都是一个事务.
private void insertFiles(Set<File> files){
SortedSet<Integer> outputFileIDs = new TreeSet<Integer>();
PreparedStatement fileExistsStatement = getFileExistsStatement();
for(File file : files) {
try {
int fileID = -1;
ResultSet rs = /* Query to see if file already present in file table */
if(rs.next()) {
// File found
fileID = rs.getInt(1);
}
if(fileID < 0) {
/* File does not exist, upload it */
rs = /* Query to get file ID */
fileID = rs.getInt(1);
}
outputFileIDs.add(fileID);
}
catch(FileNotFoundException e){
/* handle errors */
}
}
Iterator<Integer> it = outputFileIDs.iterator();
while(it.hasNext()){
/* Insert reference in output file table */
PreparedStatement outputFileStatement = "INSERT INTO output_file (file_id, /*...*/) VALUES (?, /*...*/);";
outputFileStatement.setInt(1, it.next());
outputFileStatement.executeUpdate();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是代码死锁(下面显示的异常)很多.它会在相当快乐的情况下暂停一段时间,然后死锁将在整个地方开始发生,当我们回滚并重试时,根本没有任何东西进入数据库.不过,我对于为什么它首先陷入僵局感到困惑.文件ID存储在有序集中,因此file应按照Postgres手册中的建议,以一致的顺序获取表中的锁,以防止任何死锁.我究竟做错了什么?Postgres是否以未定义的顺序运行其触发器?
org.postgresql.util.PSQLException: ERROR: deadlock detected
Detail: Process 8949 waits for ShareLock on transaction 256629; blocked by process 8924.
Process 8924 waits for ExclusiveLock on tuple (4148,40) of relation 30265 of database 16384; blocked by process 8949.
Hint: See server log for query details.
Where: SQL statement "UPDATE file
SET occurences = occurences + 1
WHERE file.file_id = NEW.file_id"
PL/pgSQL function "file_insert" line 2 at SQL statement
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at [outputFileStatement.executeUpdate(), above]
Run Code Online (Sandbox Code Playgroud)
[edit]根据axtavt的要求,事务由调用所示方法的代码管理.
public void run(){
/* connection.setAutoCommit(false) has already been called elsewhere */
try{
boolean committed = false;
boolean deadlocked = false;
synchronized(connection){
do{
deadlocked = false;
try {
/* insert lots of other stuff */
if(!files.isEmpty()){
insertFiles(files);
}
/* insert some more stuff */
connection.commit();
committed = true;
closeStatements();
}
catch(PSQLException e){
if(e.getSQLState() != null){
if(e.getSQLState().equals("40P01")){
/* Log the fact that we're deadlocked */
deadlocked = true;
}
else{
throw e;
}
}
else{
throw e;
}
}
finally {
try {
if(!committed) {
connection.rollback();
}
}
catch (SQLException e) {
/* Log exceptions */
}
}
}while(deadlocked);
}
}
catch(Exception e){
/* Log exceptions */
}
finally{
try {
connection.close();
}
catch (SQLException e) {
/* Log exceptions */
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是正在发生的事情(我怀疑):
文件元组(假设file.file_id = 1)已经存在.
进程A使用output_file.file_id = 1插入新的output_file.这将使用file.file_id = 1获取文件元组上的共享锁.
进程B使用output_file.file_id = 1插入新的output_file.这将使用file.file_id = 1获取文件元组的aharelock(多个事务可以在单个元组上保存共享块).
然后,进程A运行触发器,尝试使用file.file_id = 1更新文件元组.它不能将其共享锁提升为独占锁,因为另一个事务(进程B)持有共享锁.所以,它等待.
然后,进程B运行其触发器,该触发器尝试使用file.file_id = 1更新文件元组.由于同样的原因,它无法促进其共享锁定,因此等待......然后,我们陷入僵局.
在插入新元组之前,修复将作为新父元素的文件元组的SELECT ... FOR UPDATE; 这将在该行上创建独占锁,因此其他事务将从一开始就排队.
| 归档时间: |
|
| 查看次数: |
5912 次 |
| 最近记录: |