同事说高并发情况下, 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的情况.
想确认一下 我的上述代码能不能正确的模拟高并发更新库存的情况?
应该不会出现 数据库写操作时会使用锁 这条SQL把判断与操作写在了一起 数据库会保证操作的原子性