I’m taking an intro class on database management systems, and had a question that wasn’t answered by my book. This question is not from my homework, I was just curious.
The textbook continually stresses that a transaction is one logical unit of work. However, when coming across the shared/exclusive locking modes, I got a little confused.
There was a diagram in the book that looked like this:
Time | Transaction Status
1 Request Lock
2 Receive Lock
3 Process transaction
4 Release Lock
5 Lock is released
Does the transaction get processed all at the same time, or does it get processed as individual locks are obtained?
If there are commands in two transactions that result in a shared lock as well as an exclusive lock, do those transactions run concurrently, or are they scheduled one after the other?
The answer is, as usual, “it depends” 🙂
Generally speaking, you don’t need to take out all your locks before you begin; however, you need to take out all your locks before you release any locks.
So you can do the following:
This allows you to be a bit friendlier to other transactions that may want to read B, and don’t care about A, for example. It does introduce more risk — you may be unable to acquire a lock on B, and decide to roll back your transaction. Them’s the breaks.
You also want to always acquire all locks in the same order, so that you don’t wind up in a deadlock (transaction 1 has A and wants B; trans 2 has B and wants A; standoff at high noon, no one wins. If you enforce consistent order, trans 2 will try to get A before B and either wait, letting trans 2 proceed, or fail, if trans 1 already started — either way, no deadlock).
Things get more interesting when you have intent-to-exclude locks — locks that are taken as shared with an “option” to make them exclusive. This might be covered somewhere in the back of your book 🙂