Locking

Monay, 19 February 2001
What to do when two users wish to update the same data at the same time? Three solutions:
  1. No locking
  2. Pessimistic locking
  3. Optimistic locking

No locking

This is the simplest form. The user that updates last will win, the law of the last speaker.
User 1   Reads A Writes B
Value in database A B C
User 2   Reads A Writes C
In the example above user 2 writes last. His 'C' wins. The 'B' of user 1 gets lost.

Advantages

  • Very cheap to program, no special effort for locking
  • Suitable for systems where just one user at the time will change a value.

Disadvantages

  • User 1 gets the false impression that his 'B' has obtained persistency.
  • User 2 reads outdated information. User 2 never sees the 'B' of user 1.

Pessimistic Locking

This means a blockade for others, as long as one user is busy with some data. The blockade is pessimistic, just in case an update will follow later.
User 1   Reads A Writes B
Value in database A B C
User 2   stop Waits for user 1 Reads B Writes C

Advantages

  • Every user is sure that his updates will be processed, will be seen by other users.
  • Suitable for rather static systems with complex, time consuming updates, where most of the time only one user is working at one point in time.

Disadvantages

  • Causes an enormous delay. One user blocks all other users, even if the update does not come through in the end. One use can go for lunch during an update transaction and leave the others waiting for no reason.
  • Only one user can update data at one point in time.
  • Encourages to work slowly and delaying.

Optimistic Locking

With optimistic locking the blockade works afterwards, with a check for the right version.

The database has date and time of the latest version. During a write action the application checks of the update is using data that is still valid. A user that works with outdated data has to redo his action.

User 1   Reads A 09:00 Writes A 09:00 -> B
Value in database A 09:00 B 10:15 C 11:30
User 2   Reads A 09:00 Writes A 09:00 -> C stop Reads B 10:15 Writes B 10:15 -> C  

Advantages

  • Once confirmed by the system, every user is sure that his updates have been processed and will be seen by other users.
  • Suitable for systems in a dynamic environment, with many users that do short, fast updates.
  • Users are not blocking each other. The one with the first write action wins.
  • Encourages users to work fast.

Disadvantages

  • A user is only sure of success after the write action has finished.
  • Bad for time consuming updates.

Till next week,
Nut