Exclusive lock and Shared Lock

Both these locks are usually used in the Database in order to ensure control over the transactions that happen concurrently at the same time (the time gap are possibly in milliseconds). They are also used to isolate the transaction, for security reasons and maintain consistency over the data.

Exclusive lock (X)

It is also referred as write lock. This lock is usually used when we are updating to the value or row or the column in a database but we want no other connection who is attempting to read the same value get stale value i.e. the value it was before being updated and maintain consistency over the data. The connection trying to read the data will generally get an error.

Lets take a real life example of it.

Say you want to see to your bank balance. You open your bank app and tap on 'Check Balance'. But unfortunately you get an error. The possible reason is that someone might be transferring money into your account, if it so, then while updating your balance there is use of exclusive lock in the row of your data inside the database and the same was preventing you to check your balance.

Shared lock (S)

It is also called read lock. It usually applied to the value or row or the column while reading from the database. The general idea is that we want the value to remain same or not get updated till we complete our transaction. The connection trying to update the value get an error.

Lets again take an real life instance of it.

Say you want to generate report using some data from the database and you have completed half of it. Meanwhile the database receive a request to update the value or data you have used in your report. So, at that time the database accept the update then your report will have in-consistence data. So, in order to stop this from happening shared lock is used to ensure consistency of data across the transaction.

Note: Only one lock can be used at a time and In order to use another lock the first one should be released.