Actually For Such situations Optimistic locking should be used . It can be used below way :
- User requests from UI to get record to edit .
- Server selects the record and pass them to UI . Suppose at this time record
to be edited was having version 1 . Now database conncetion is released . No
Database resources are held as we don't know if user will issue update request
or not .
- Now user edits data on UI and requests for its update to server with the
original version number that was sent in step 2.
- Now a new database conncetion is taken from db connection pool and record is
updated in db if original record present in db has the same version as it was
sent to UI in step 2. It version of the record present in step 4 has been
changed before used sends the edit request you should ask user to edit again
with fresh data .
In the above scenario no db resources are held upto the duration of whole conversation of user.
Generally speaking in such scenarios optimistic locking is good .
But If it is very critical to hold the resources with write locks until the transaction commits then Pessimitic should be used
For example suppose a simple movie ticket booking system which doesn't hold seets for user who has not done payment yet . Means after payment they may or may not get the tickets . When after payment they reuqest booking engine to book the ticket .
- Suppose there is table in db which holds number of seets left in a show .
- Tx1 takes a pessimitic write lock of this table .
- Until the transaction TX1 to book a movie commits not any other transaction can
take lock of this table.
- When Tx1 completes it decreases the seat count by number of seets booked in Tx1
- Now when Tx2 gets the write lock and if number of seets left are compatible it
proceeds if not it present user with a message that seats got booked by other
user and payment is refunded .
In this situation holding Pessimitic lock until the booking transaction completes make sense . Even in this situation no locks and transactions are held in user's
complete convesation .
Pessimistic read or Pessimitic Write locks are held until a transaction is committed or rolled back . Only Pessimitic read locks can be shared all other combinations block each other until released .