java - 代码评审: 是否能正确模拟并发更新数据库库存的情况
巴扎黑
巴扎黑 2017-04-17 17:09:20
[Java讨论组]

同事说高并发情况下, 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的情况.

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

巴扎黑
巴扎黑

全部回复(1)
PHP中文网

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号