我的表totalAmount
中有purchasedItems
和items
个项目列。如果purchasedItems
,我想自动更新totalAmount >= purchasedItems + 1
,否则我想抛出一个错误。我试图做这样的事情,但失败了。如何原子地实现这一点(我正在使用Java jdbc做到这一点)?
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
DECLARE @purchased AS INT
DECLARE @total AS INT
SELECT @purchased = SELECT (purchasedItems + 1) FROM events WHERE id=1
SELECT @total = SELECT totalAmount FROM items WHERE id=1
IF @purchased > @total
BEGIN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Max value passed'
END
# ELSE DO UPDATE
SELECT @remaining
COMMIT TRANSACTION
永远不会抛出错误消息
答案 0 :(得分:0)
如果我开始交易并进行检查以检查我的条件是否合格,然后更新表,那么另一个进程无法在获取和更新之间进行更新,对吗?
是正确的,但是即使使用SERIALIZABLE事务隔离,如果多个进程尝试使用“检查然后更新并提交”策略,您仍然会遇到死锁。考虑一个简化的示例,其中的代码只是想将purchasedItems
最多增加10:
try (Connection conn = DriverManager.getConnection(connectionUrl, myUid, myPwd)) {
conn.setAutoCommit(false);
conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
final int maxPurchasedItems = 10;
Statement st = conn.createStatement();
System.out.println("Initial SELECT ...");
Long t0 = System.nanoTime();
ResultSet rs = st.executeQuery("SELECT purchasedItems FROM items WHERE id = 1");
rs.next();
int n = rs.getInt(1);
System.out.printf("Original value: %d (%d ms)%n",
n, (System.nanoTime() - t0) / 1000000);
if (n >= maxPurchasedItems) {
System.out.printf("Increment would exceed limit of %d. Cancelled.%n", maxPurchasedItems);
conn.rollback();
} else {
Thread.sleep(5000);
t0 = System.nanoTime();
System.out.println("Attempting UPDATE ...");
st.executeUpdate("UPDATE items SET purchasedItems = purchasedItems+1 WHERE id = 1");
rs = st.executeQuery("SELECT purchasedItems FROM items WHERE id = 1");
rs.next();
n = rs.getInt(1);
System.out.printf("Updated value: %d (%d ms)%n",
n, (System.nanoTime() - t0) / 1000000);
Thread.sleep(5000);
conn.commit();
}
} catch (Throwable ex) {
ex.printStackTrace(System.err);
}
如果我们尝试在两个独立的进程中同时运行该代码,则会看到
Process_A:
Initial SELECT ...
Original value: 6 (142 ms)
Attempting UPDATE ...
Updated value: 7 (1910 ms)
Process_B:
Initial SELECT ...
Original value: 6 (144 ms)
Attempting UPDATE ...
com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
那是因为Process_A的初始SELECT在该行上放置了写锁。这只是一个写锁,因此允许Process_B的初始SELECT继续进行。但是,这也会在行上放置写锁,因此两个事务将陷入死锁。 MySQL必须选择要杀死的事务,而Process_B是不幸的。
相反,您应该使用“更新然后检查并在必要时回滚”策略:
try (Connection conn = DriverManager.getConnection(connectionUrl, myUid, myPwd)) {
conn.setAutoCommit(false);
final int maxPurchasedItems = 10;
Statement st = conn.createStatement();
System.out.println("Initial UPDATE ...");
Long t0 = System.nanoTime();
st.executeUpdate("UPDATE items SET purchasedItems = purchasedItems+1 WHERE id = 1");
ResultSet rs = st.executeQuery("SELECT purchasedItems FROM items WHERE id = 1");
rs.next();
int n = rs.getInt(1);
System.out.printf("Updated value: %d (%d ms)%n",
n, (System.nanoTime() - t0) / 1000000);
Thread.sleep(5000);
if (n > maxPurchasedItems) {
System.out.printf("Increment exceeds limit of %d. Rolling back.%n", maxPurchasedItems);
conn.rollback();
} else {
conn.commit();
}
} catch (Throwable ex) {
ex.printStackTrace(System.err);
}