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

后端 未结 5 1526
既然无缘
既然无缘 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 04:57

    Here is a detailed answer to this question: How to properly handle two threads updating the same row in a database To summarize:

    The biggest question is: Are the two threads trying to persist the same data ?To summarize the content of the linked answer. Lets name the two threads T1 and T2. There are couple of aproaches:

    Approach 1, this is more or less the last to update Wins situation. It more or less avoids the optimistic locking (the version counting). In case you don't have dependency from T1 to T2 or reverse in order to set status PARSED. This should be good.

    Aproach 2 Optimistic Locking This is what you have now. The solution is to refresh the data and restart your operation.

    Aproach 3 Row level DB lock The solution here is more or less the same as for approach 2 with the small correction that the Pessimistic lock dure. The main difference is that in this case it may be a READ lock and you might not be even able to read the data from the database in order to refresh it if it is PESSIMISTIC READ.

    Aproach 4 application level synchronization There are many different ways to do synchronization. One example would be to actually arrange all your updates in a BlockingQueue or JMS queue(if you want it to be persistent) and push all updates from a single thread. To visualize it a bit T1 and T2 will put elements on the Queue and there will be a single T3 thread reading operations and pushing them to the Database server.

提交回复
热议问题