In: Computer Science
Q)
A shared lock is issued when a transaction must read data from the database and no exclusive locks are held on the data to be read.” Is it correct? Justify the answer by explaining the conditions (or by an example) under which both types of locks are granted
Please find the answers below.
"A shared lock is issued when a transaction must read data from the database and no exclusive locks are held on the data to be read.” This statement is correct.
There are two types of locks. 1) Shared Lock (S) 2) Exclusive Lock (X)
While holding shared lock the transaction does not have the permission to update data on the data item. A shared lock is also called a Read-only lock. With the shared lock, the data item can be shared between transactions. This is because there will not be any permission to update data on the data item. For example, consider a case where two transactions are reading the account balance of a person. The database will let them read by placing a shared lock. However, if another transaction wants to update that account's balance, shared lock prevent it until the reading process is over.
In exclusive lock (X) data item can be both read as well as written.This is exclusive and cannot be held simultaneously on the same data item. Transactions may unlock the data item after finishing the 'write' operation. For example, when a transaction needs to update the account balance of a person. This can be allowed by placing X lock on it. Therefore, when the second transaction wants to read or write, exclusive lock prevent this operation.
If a transaction A holds a shared lock on item N, then a request from another transaction B for an exclusive lock on N will cause B to go into a wait state until A releases the lock. A request from transaction B for a shared lock on N will be granted. So, B will now also hold a shared lock on N.
If transaction A holds an exclusive lock on record N, then a request from transaction B for a lock of either type on N will cause B to go into a wait state and B will wait until A releases the lock.
This can be summarised by means of the compatibility matrix below, that shows which type of lock requests can be granted simultaneously:
Type of lock N that transaction B requests for data item N | Types of lock that transaction A hold on data item N | ||
Exclusive lock (X) | Shared lock (S) | No lock | |
Exclusive lock (X) | No | No | Yes |
Shared lock (S) | No | Yes | Yes |
No lock | Yes | Yes | Yes |