简体   繁体   中英

mysql - Row locking and releasing

I have two table 'reservation' and 'spot'.during a reservation process the 'spotStatus' column in spot table is checked and if free, it is to be updated. A user is allowed to reserve only one spot so to make sure that no other user can reserve the same spot, what can i do?

referring to some answers here,i found row locking,table locking as solutions. should i perform queries like

"select * from spot where spotId = id for update;" 

and then performing necessary update to the status or is there other elegant ways to do it?

and my concern is what happens to the locked row if

1. Transaction doesnot complete successfully?  
2. what happens if both user tries to reserve the same row at the same time? are both transactions cancelled? 

and when is the lock released?

  1. if its not successful, the database returns to the same data it was before the transaction (rollback) as if it never happened.
  2. the same as it was not in the same time. only one of them will lock the db and the other wont be created.

The problem here is in race conditions, that even transactions will not prevent by default if used naively - even if 2 reservations happen simultaneously, for example originating from 2 different Apache processes running PHP, transactional locking will just ensure the reservations are properly serialized, and as such the second one will still overwrite the first.

Usually this situation is of no real concern, given the speed of databases and servers as a whole, compared to the load on an average reservation site, the chances of this ever causing a problem are less than winning the state lottery twice in a row. If however you are implementing a site that's going to sell 50k Coldplay concert tickets in 30 seconds, chances rise aggressively.

A simple solution to this is to implement a sort of 'reservation intent' by not overwriting the spot reservation directly, but by appending the intent-to-reserve to a separate timestamped table. After this insertion you can then clean up this table for duplicates, preferring the oldest, and apply that one to the real-time data.

如果使用的是Teradata,则可以使用队列表概念。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM