1
我試圖想出一個處理事務鎖及其恢復的解決方案。如何處理Java中的事務鎖(Postgresql)
我有下面這樣的代碼:
try {
Connection conn = DriverManager.getConnection(url, userName, password);
Connection conn2 = DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(false);
conn2.setAutoCommit(false);
conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
conn2.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
Statement stmt = conn.createStatement();
Statement stmt2 = conn2.createStatement();
stmt.setQueryTimeout(100);
stmt.executeUpdate("update layout set HEIGHT = 45 where ID = 2");
stmt2.setQueryTimeout(10);
stmt2.executeUpdate("update layout set HEIGHT = 12 where ID = 2");
conn2.commit();
conn.commit();
System.out.println("Done....");
}
//TODO: should be throwing it back..
catch (Exception e) {
e.printStackTrace();
}
現在我更新layout
表中兩個獨立的交易。現在這會導致鎖定,因此我使用setQueryTimeout
重新覆蓋了這種情況。
但我不確定setQueryTimeout
是否是處理事務鎖定和恢復的正確方法。還有其他的最佳做法嗎?
請注意,我沒有使用任何ORM的普通Java。
很少理論,'悲觀鎖定'和'樂觀鎖定'是你知道的嗎?總的來說很難說如何做'恢復',因爲許多場景和許多要求都可以存在。這是企業軟件中的重要問題之一 –
想象一下銀行或大型互聯網商店,而你是客戶。應該設計什麼'交易恢復策略'? –
@JacekCz:對不起,我不知道這一點。 – batman