代码评审: 是否能正确模拟并发更新数据库库存的情况

同事说高并发情况下, mysql会存在这样的问题

update product set count = count - 1 where id = ? and count>0

最终会有count小于0的情况 我觉得不可能 于是用java写了一段代码 模拟并发更新count的情况

        int nThreads = 140; //不要超过数据库最大连接数 : max_connections  151 
        ExecutorService pool = Executors.newFixedThreadPool(nThreads);
        CountDownLatch startLatch = new CountDownLatch(nThreads);
        CountDownLatch endLatch = new CountDownLatch(nThreads);
        for (int i = 0; i < nThreads; i++) {
            pool.submit(() -> {
                startLatch.countDown();
                try { startLatch.await(); } catch (Exception e1) { } //等待所有任务都提交了再往下执行 保证并发
                
                String sql = "update t set count = count-1 where id =1 and count>0";
                try {
                    Connection connection = DriverManager.getConnection(url, user, password);
                    Statement stat = connection.createStatement();
                    stat.execute(sql);
                    endLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        endLatch.await(); //等待所有的任务都完成
        System.out.println("done");
        System.exit(0);

数据库表

root@localhost:[test]09:04:05>select * from t;
+----+-------+
| id | count |
+----+-------+
|  1 |     1 |
+----+-------+

没有发现count会有小于0的情况.

想确认一下 我的上述代码能不能正确的模拟高并发更新库存的情况?

阅读 3.8k
1 个回答

应该不会出现 数据库写操作时会使用锁 这条SQL把判断与操作写在了一起 数据库会保证操作的原子性

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题