8

I've heard about many application developers having a bit of trouble in regards to race conditions in database processing. A typical example goes something like this:

  • User 1 selects a field, say, numStock, which is 3
  • User 2 also selects numStock, which is still 3
  • User 1 decrements numStock (in the app), and sets it to 2 in the database.
  • User 2 also decrements numStock (in the app), and sets it to 2 in the database.

In this example, the numStock field should have become 1, but it was set to 2 instead due to the race between users.

So of course locks can be used, but I've thought of another way of handling this - passing all row details as WHERE criteria. Let me explain...

In the example above, the SQL codes might look like this:

//select

SELECT itemID, numStock FROM items WHERE itemID = 45

//update

UPDATE items SET numStock = 2 WHERE itemID = 45

My idea for resolving the race:

//select

SELECT itemID, numStock FROM items WHERE itemID = 45

//update

UPDATE items SET numStock = 2 WHERE itemID = 45 AND numStock = 3

Thus, the query checks if the data has changed since it SELECT-ed the data. So my question is: (1) Would this [always] work? and (2) is this a better option compared to database locking mechanisms (eg, MySQL Transactions)?

Thanks for your time.

4

3 に答える 3

9

この戦略は機能し、「楽観的ロック」として知られています。これは、処理が成功すると仮定して処理を行い、最後にのみ実際に成功したかどうかを確認するためです。

もちろん、トランザクションを再試行する方法が必要です。また、失敗の可能性が非常に高い場合は、非効率になる可能性があります。しかし、ほとんどの場合、問題なく動作します。

于 2012-03-24T08:56:53.977 に答える