Multiple threads update same row in database at a time how to maintain consistence

后端 未结 5 1523
既然无缘
既然无缘 2021-01-14 04:19

In my java application multiple threads update same row at a time how to get consistence results ?

for example

current row value count =0; 
thread 1          


        
5条回答
  •  隐瞒了意图╮
    2021-01-14 05:08

    Incrementing a counter in this way is hard to manage concurrently. You really need to use pessimistic locking to solve this particular problem.

    SELECT 1 FROM mytable WHERE x IS TRUE FOR UPDATE
    

    This will force each thread to wait until the previous one commits before it reads the counter.

    This is necessary because you have two potential issues, the first is the read race and the second is the write lock. The write lock gets taken automatically in most RDBMSs but unless you take it explicitly before you read, the counter will be incremented once by both threads together (because both read the original value before the update).

    If you need to have parallel writes, then you need to insert a table and then materialize an aggregate later. That is a more complex design pattern though.

提交回复
热议问题