java—事务中值的条件更新

rnmwe5a2  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(339)

我有一个 totalAmount 以及 purchasedItems “我的表中的项目数”列 items . 我想要原子更新 purchasedItems 如果: totalAmount >= purchasedItems + 1 ,否则我想抛出一个错误。我试过这样做,但失败了。如何以原子方式实现这一点(我是用javajdbc实现的)?

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

不会抛出错误消息

j2qf4p5b

j2qf4p5b1#

如果我启动一个事务并执行get来检查我的条件传递,然后更新表,那么在get和update之间的另一个进程就不能更新了,对吗?
这是正确的,但是即使使用可序列化事务隔离,如果多个进程尝试使用“检查然后更新并提交”策略,您仍然会遇到死锁。考虑一个简化的示例,其中代码只想递增 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);
}

如果我们尝试在两个独立的进程下同时运行代码,我们会看到
工艺流程图a:

Initial SELECT ...
Original value: 6 (142 ms)
Attempting UPDATE ...
Updated value: 7 (1910 ms)

工艺流程:

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

这是因为进程a的初始选择在行上放置了写锁。它只是一个写锁,所以允许进程\u b的初始选择继续。但是,这也会在行上放置写锁,因此这两个事务处于死锁状态。mysql必须选择一个事务来终止,而进程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);
}

相关问题