Ticker

6/recent/ticker-posts

DBMS

EDUKOSAL

Transaction Management

Database Management Systems • UG Study Notes

Visual notes • Worked examples • Question bank with answers

CHAPTER 1 OF 5 • READ-ONLY EDITION

www.edukosal.com

Table of Contents (Book Plan)

  1. Chapter 1 – Transactions, ACID Properties and Schedules
  2. Chapter 2 – Concurrent Execution, Serializability and Recoverability
  3. Chapter 3 – Lock-Based Concurrency Control, Two-Phase Locking (2PL), Lock Management and Performance of Locking
  4. Chapter 4 – Dealing with Deadlocks
  5. Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery; Final Revision, References

Inside Chapter 1: 1.1 Introduction • 1.2 Transaction and its operations • 1.3 Transaction states • 1.4 ACID properties • 1.5 Real-life examples • 1.6 Transactions and schedules • 1.7 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary

EDUKOSAL • UG DBMSUnit: Transaction ManagementChapter 1
CHAPTER 1

Transactions, ACID Properties and Schedules

Learning Outcomes After this chapter you will be able to: define a transaction; draw and explain transaction states; explain Atomicity, Consistency, Isolation and Durability with examples; identify which DBMS component supports each property; define schedules and distinguish serial, non-serial (interleaved) and complete schedules.

1.1 Introduction

Whenever you pay using UPI, book a train ticket or withdraw cash from an ATM, several database changes must happen together. Money must leave one account and reach another. A seat must be marked booked and a ticket must be issued. If only half of these steps succeed, the data becomes wrong and people lose money or seats.

A DBMS solves this problem with the idea of a transaction. It also lets thousands of users work at the same time without disturbing one another, and it protects completed work even if the system crashes. These guarantees are the foundation of banking, railway, e-commerce and every other serious database application. That is why Transaction Management is a core topic in every university DBMS course.

1.2 Meaning, Definition and Operations of a Transaction

Simple DefinitionA transaction is a group of database steps that must be treated as one single job: either all steps happen, or none of them happen.
Academic DefinitionA transaction is a logical unit of work consisting of one or more database operations (reads and writes) that, when executed alone on a consistent database, takes it to another consistent database state. A DBMS sees a transaction as a series of read and write operations on database objects, followed by a commit or an abort.

Basic operations

OperationMeaning
READ(X)Copy data item X from the database (disk) into a program variable in main memory.
WRITE(X)Write the program variable back to X in the database.
COMMITDeclare the transaction successful; all its changes must become permanent.
ABORT / ROLLBACKDeclare the transaction unsuccessful; all its changes must be undone.

Note: the DBMS only “sees” reads and writes. Calculations such as A = A - 500 happen in the program’s memory and are invisible to the DBMS. Because of this, the DBMS cannot know what a transaction means; it only controls the order of reads and writes.

Working process: funds transfer transaction

BEGIN READ(A) A = A - 500 WRITE(A) READ(B) B = B + 500 WRITE(B) COMMIT What if the system fails somewhere in the middle? FAILURE (power cut, error, deadlock) after WRITE(A) but before WRITE(B) ROLLBACK: undo write to A
Figure 1.1: Steps of a funds-transfer transaction (A pays ₹500 to B) and what happens on failure.

1.3 Transaction States

A transaction passes through well-defined states from its start to its end. The DBMS tracks the state to decide whether to keep or undo its work.

ACTIVE PARTIALLYCOMMITTED COMMITTED FAILED ABORTED last statement changes made safe error write fails rollback Committed and Aborted are the two terminal (final) states.
Figure 1.2: Transaction state diagram.
StateDescription
ActiveInitial state. The transaction is executing its read/write operations.
Partially committedThe final statement has executed, but the changes may still sit in memory buffers and are not yet guaranteed safe on disk.
CommittedSuccessful completion. The changes are permanent (recorded safely in the log) and will survive a crash.
FailedNormal execution cannot continue because of an error, a crash, or a decision of the DBMS.
AbortedThe transaction has been rolled back and the database is restored to its state before the transaction began. The transaction can then be restarted (if the failure was not a logical error) or killed.

1.4 ACID Properties

To keep data correct, every DBMS transaction must satisfy four properties, remembered by the word ACID.

TRANSACTIONACID A – AtomicityAll or nothingManaged by: Recovery manager C – ConsistencyValid state to valid stateManaged by: Programmer + constraints I – IsolationAppears to run aloneManaged by: Concurrency control D – DurabilityCommitted work survives crashesManaged by: Recovery manager (log)
Figure 1.3: Concept map of ACID properties and the DBMS parts that support them.

A – Atomicity

DefinitionEither all actions of a transaction are carried out, or none are. The transaction is an indivisible (atomic) unit.

If a transaction fails midway, the DBMS must undo the partial changes already made. The DBMS keeps a log of every write so that it can restore old values. Atomicity is the responsibility of the recovery manager.

Example: Debiting A and crediting B. If the system crashes after debiting A, atomicity demands that A’s debit is undone.

C – Consistency

DefinitionA transaction run by itself on a consistent database must leave the database consistent, that is, satisfying all integrity rules (primary key, foreign key, CHECK constraints, business rules).

Consistency is mainly the user’s (application programmer’s) responsibility, supported by the DBMS through integrity constraints. For example, in a transfer, the total balance A + B must stay the same before and after. The DBMS can enforce declared constraints such as balance >= 0 but cannot know your unwritten business rules.

I – Isolation

DefinitionA transaction must be protected from the effects of other transactions running at the same time. Each transaction should appear to execute as if it were running alone, even though the DBMS interleaves their operations.

Isolation is ensured by the concurrency control component (for example, the lock manager). The usual meaning is that the final result must equal the result of some serial execution of the transactions. This idea, called serializability, is studied in Chapter 2. Note that the DBMS does not promise which serial order is used.

D – Durability

DefinitionOnce a transaction is committed, its changes must persist, even if the system crashes immediately afterwards.

The DBMS records the changes in a log on stable storage before declaring the commit successful (this is the write-ahead logging idea, introduced in Chapter 5). After a crash, the recovery manager redoes committed work that had not yet reached the disk.

Summary table

PropertyQuestion it answersThreatened byEnsured by
AtomicityDid all steps happen or none?Failure/abort midwayLog + undo (recovery manager)
ConsistencyAre all rules still satisfied?Faulty transaction logic, rule violationsProgrammer, integrity constraints
IsolationDo concurrent users disturb each other?Interleaved executionLocking / concurrency control
DurabilityWill committed data survive a crash?Crash before data reaches diskLog + redo (recovery manager)
Remember ThisAtomicity and Durability are both handled by the recovery manager (undo for atomicity, redo for durability). Isolation is handled by concurrency control. Consistency is shared between the programmer and the DBMS constraints.

1.5 Real-Life Examples

LevelSituationHow the concept works
EverydayBuying tea at a stall: you hand over ₹20 and the seller hands over tea.Either both exchanges happen or neither (atomicity). If the seller has no tea, you take your money back (rollback).
IndustryE-commerce order: reduce stock, create order record, charge payment.All three updates form one transaction. If payment fails, stock reduction is undone. Two buyers of the last item are kept apart by isolation.
IndianUPI payment from your bank account to a shopkeeper’s account; IRCTC Tatkal ticket booking.Debit and credit are atomic. Once “payment successful” appears, it is durable even if servers restart. For IRCTC, isolation stops two users from getting the same last seat.

Example 1: Basic Example

Problem / Situation: Account A has ₹5,000 and account B has ₹3,000. Transaction T transfers ₹500 from A to B.
Explanation: T reads both balances, changes them in memory and writes them back.
Step-by-step solution:
  1. READ(A): A = 5000
  2. A = A − 500 = 4500
  3. WRITE(A)
  4. READ(B): B = 3000
  5. B = B + 500 = 3500
  6. WRITE(B)
  7. COMMIT
Final result: A = ₹4,500, B = ₹3,500. Total before = 8,000; total after = 8,000, so the database is consistent. If a crash occurs after step 3, atomicity requires A to be restored to ₹5,000.

Example 2: Real-Life Application

Real-world situation: A cinema booking site shows one seat left. Two users click “Book” at the same moment.
How the concept is applied: Each booking is a transaction. Isolation makes the DBMS process them as if one came after the other, so only the first succeeds; the second sees the seat as taken. Atomicity makes sure that seat marking, payment and ticket creation succeed together.
Learning outcome: Isolation prevents double booking, atomicity prevents half-finished bookings.

Example 3: Practical / Case Study

Background: A bank’s server crashes at the exact moment it is processing a customer’s transfer of ₹10,000.
Problem: After restart, the customer’s account shows ₹10,000 less, but the beneficiary has not received it.
Application of the concept: The recovery manager reads the log. It finds that the transfer transaction has no commit record, so it is treated as a failed transaction and its debit is undone (atomicity). Another transfer that had committed just before the crash, but whose data was still only in memory, is redone from the log (durability).
Result: Both accounts are in a correct state after recovery.
Conclusion: The log makes atomicity and durability possible together.

1.6 Transactions and Schedules

A real DBMS runs many transactions at once. To study their behaviour we use the idea of a schedule.

Definition: ScheduleA schedule is a list of actions (reads, writes, commits, aborts) from a set of transactions, in which the order of actions within each transaction is preserved. Actions of different transactions may be mixed (interleaved).

Notation

Ri(X) = transaction Ti reads X. Wi(X) = Ti writes X. Commiti and Aborti end Ti.

Types of schedules

TypeMeaningExample
Serial scheduleActions of different transactions are not interleaved; each transaction runs completely before the next starts.R1(A) W1(A) C1 R2(A) W2(A) C2
Non-serial (interleaved / concurrent) scheduleActions of different transactions are mixed in time.R1(A) R2(A) W1(A) W2(A) C1 C2
Complete scheduleContains a commit or an abort for every transaction listed in it.Any schedule above that ends with C1, C2 (or Ai).
Serial schedule T1: R(A) W(A) R(B) W(B) Commit T2: R(A) W(A) R(B) W(B) Commit time → Interleaved (non-serial) schedule T1: R(A) W(A) T2: R(A) W(A) T1: R(B) W(B) C T2: R(B) W(B) C time → Blue = T1, Orange = T2. In the interleaved case their actions alternate. Whether such an interleaving is safe is decided by serializability (Chapter 2).
Figure 1.4: Serial and interleaved schedules for two transactions.

Number of serial schedules

For n transactions there are n! possible serial schedules (for 2 transactions: 2; for 3: 6; for 4: 24). The number of possible interleaved schedules is much larger, so a DBMS needs a rule to decide which ones are safe.

Worked Example: Two serial schedules, two correct results

Situation: A = 1000, B = 1000.
T1: transfer ₹100 from A to B (A = A − 100; B = B + 100).
T2: add 10% interest to both accounts (A = A × 1.1; B = B × 1.1).
Serial orderCalculationFinal AFinal BA + B
T1 then T2(900, 1100) then × 1.199012102200
T2 then T1(1100, 1100) then transfer100012002200
Learning outcome: Different serial orders may give different final states, yet both are correct, because each leaves the database consistent (the total is 2200 in both). A DBMS only promises that a concurrent execution is equal to some serial order, not a particular one.

1.7 Applications, Advantages and Limitations

Applications

  • Banking and payments: NEFT, UPI, ATM withdrawals, loan processing.
  • Transport and travel: railway and airline seat reservation.
  • E-commerce and business: order placement, inventory, billing.
  • Education: university admission and result systems where thousands of students use the portal together.
  • Healthcare and government: patient records, Aadhaar-linked services, tax filing.
Advantages of the transaction conceptLimitations
Data stays correct despite failures.
Many users can work at once safely.
Committed work is never lost.
Simplifies application programming: programmers think about one transaction at a time.
Logging and locking add overhead and reduce speed.
Long transactions can block others.
Strict isolation can reduce concurrency.
Failures may force a transaction to be restarted.

Important Points for Revision

Key Terminology Transaction – logical unit of work. Commit – make changes permanent. Rollback / Abort – undo changes. Log – record of all changes kept on stable storage. Schedule – ordered list of actions from several transactions. Serial schedule – no interleaving. Interleaving – mixing actions of different transactions.
Exam Tips Always draw the state diagram and the ACID concept map; examiners reward diagrams. For ACID, write definition, example and the responsible DBMS component for each property. For schedules, write at least one example using R and W notation.
Common Mistakes Saying that the DBMS itself guarantees consistency of all business rules (it enforces only declared constraints). Confusing partially committed with committed. Saying that isolation means transactions run one by one (they may interleave; the effect must equal a serial order). Forgetting that a crash after commit must not lose data.

Difference Between Important Concepts

BasisAtomicityDurability
ConcernsUncommitted / failed transactionsCommitted transactions
MechanismUNDO using logREDO using log
GuaranteeNo partial effectsNo loss of committed effects
BasisSerial scheduleNon-serial schedule
InterleavingNonePresent
PerformancePoor (no concurrency)Better (CPU and disk used well)
CorrectnessAlways correctCorrect only if equivalent to a serial schedule
BasisCOMMITROLLBACK
EffectMakes changes permanentUndoes all changes
Final stateCommittedAborted

Important formulas: Number of serial schedules of n transactions = n!.

QUESTION BANK

Chapter 1: Questions with Answers

A. Multiple Choice Questions (20)

Q1. A transaction is best described as:
A. A logical unit of work that is performed completely or not at all
B. A single SQL SELECT statement
C. A table in a database
D. A backup copy of data
Answer: A. A transaction groups operations into one logical unit that must be all-or-nothing.
Q2. Atomicity means:
A. Data is stored in small units
B. All operations of a transaction happen or none do
C. Transactions run only one at a time
D. Data is encrypted
Answer: B. Atomicity is the “all or nothing” property.
Q3. Which DBMS component is mainly responsible for atomicity and durability?
A. Query optimizer
B. Lock manager
C. Recovery manager
D. Parser
Answer: C. The recovery manager uses the log to undo (atomicity) and redo (durability).
Q4. Isolation is mainly enforced by:
A. Recovery manager
B. Concurrency control (lock manager)
C. Disk controller
D. Report generator
Answer: B. Concurrency control, for example locking, keeps concurrent transactions from interfering.
Q5. After a transaction executes its final statement, it enters the:
A. Active state
B. Aborted state
C. Partially committed state
D. Failed state
Answer: C. Only after the changes are made safe does it move to Committed.
Q6. A transaction that can no longer proceed normally is in the:
A. Failed state
B. Committed state
C. Active state
D. Partially committed state
Answer: A. From the Failed state it moves to Aborted after rollback.
Q7. After rollback is complete, the transaction is in the:
A. Active state
B. Committed state
C. Partially committed state
D. Aborted state
Answer: D. Aborted means all effects have been undone.
Q8. Which statement makes the changes of a transaction permanent?
A. ROLLBACK
B. COMMIT
C. SELECT
D. DROP
Answer: B. COMMIT ends the transaction successfully and makes its changes permanent.
Q9. Consistency requires that a transaction:
A. Takes the database from one consistent state to another consistent state
B. Never reads any data
C. Always runs in parallel
D. Is executed twice
Answer: A. All integrity rules must hold before and after the transaction.
Q10. A = 2000 and B = 1000. After a successful transfer of ₹300 from A to B, A + B equals:
A. 2700
B. 3300
C. 3000
D. 2000
Answer: C. A = 1700, B = 1300, so the sum remains 3000.
Q11. A schedule in which transactions execute one after another without interleaving is called:
A. Concurrent schedule
B. Serial schedule
C. Partial schedule
D. Deadlock schedule
Answer: B. No actions of different transactions are mixed.
Q12. For 4 transactions, the number of possible serial schedules is:
A. 4
B. 8
C. 16
D. 24
Answer: D. 4! = 24.
Q13. In any schedule, the order of actions inside each individual transaction is:
A. Preserved
B. Reversed
C. Randomised
D. Ignored
Answer: A. A schedule can interleave transactions but never reorder a transaction’s own actions.
Q14. In schedule notation, R1(A) means:
A. T1 writes A
B. T1 commits
C. T1 reads A
D. T1 aborts
Answer: C. R denotes read and the subscript is the transaction number.
Q15. A power failure occurs right after a transaction commits. Which property ensures its changes are not lost?
A. Atomicity
B. Durability
C. Isolation
D. Consistency
Answer: B. Durability keeps committed changes safe through crashes.
Q16. Which command cancels all changes made by the current transaction?
A. ROLLBACK
B. COMMIT
C. GRANT
D. UPDATE
Answer: A. ROLLBACK aborts the transaction and undoes its changes.
Q17. Money is debited from one account but never credited to the other because of a crash. Which property is violated?
A. Isolation only
B. Durability only
C. Neither
D. Atomicity
Answer: D. Only part of the transaction took effect.
Q18. Responsibility for maintaining consistency of business rules lies mainly with:
A. The disk drive
B. The operating system scheduler
C. The application programmer, supported by integrity constraints
D. The network administrator
Answer: C. The DBMS enforces declared constraints, but the programmer must write correct transaction logic.
Q19. An interleaved schedule is also called a:
A. Serial schedule
B. Concurrent (non-serial) schedule
C. Empty schedule
D. Backup schedule
Answer: B. Actions of different transactions are mixed in time.
Q20. A complete schedule is one that:
A. Has only read actions
B. Has only one transaction
C. Has no writes
D. Contains a commit or abort for every transaction in it
Answer: D. Every transaction listed has ended by committing or aborting.

B. Very Short Answer Questions (10)

1. What is a transaction?
A transaction is a logical unit of work made up of reads and writes on the database. It must execute completely or not at all, and it ends with a commit or an abort.
2. Expand ACID.
ACID stands for Atomicity, Consistency, Isolation and Durability. These are the four properties that a DBMS transaction must satisfy.
3. What is a rollback?
Rollback undoes all changes made by an incomplete or failed transaction. The database returns to the state it had before the transaction began.
4. What is the use of the log?
The log records every change made by transactions on stable storage. The recovery manager uses it to undo failed transactions and redo committed ones.
5. Name the five transaction states.
Active, partially committed, committed, failed and aborted. Committed and aborted are the final states.
6. What is a schedule?
A schedule is an ordered list of actions (read, write, commit, abort) from a set of transactions. The order of actions within each transaction is preserved.
7. What is a serial schedule?
It is a schedule in which one transaction runs completely before the next starts, so there is no interleaving of actions.
8. How many serial schedules exist for n transactions?
There are n! (n factorial) serial schedules. For three transactions this gives 3! = 6 schedules.
9. Which component ensures isolation?
The concurrency control component, usually implemented by a lock manager, ensures isolation. It controls access to shared data items.
10. What is a complete schedule?
A complete schedule has a commit or an abort action for every transaction that appears in it. Thus every transaction in it has finished.

C. Short Answer Questions (10)

1. Explain atomicity with an example.
Atomicity means that all operations of a transaction are performed, or none are. Take a transfer of ₹500 from A to B. The transaction debits A and then credits B. If the system fails after the debit, A has lost money while B has gained nothing. To prevent this, the DBMS keeps a log of the old value of A. During recovery it finds that the transaction never committed and restores A to its old value. The transfer therefore appears as if it never began. Atomicity is implemented by the recovery manager using the log and the undo operation.
2. Explain durability.
Durability guarantees that once a transaction commits, its changes persist even if the system crashes immediately afterwards. Disk writes may be delayed in memory buffers, so the DBMS first writes log records to stable storage and only then reports the commit to the user. If a crash occurs, the recovery manager reads the log and redoes any committed changes that did not reach the database disk. This is why a “payment successful” message in a UPI app can be trusted.
3. Differentiate between COMMIT and ROLLBACK.
COMMIT ends a transaction successfully and makes all its changes permanent and visible to others. After commit, the changes cannot be undone by the transaction. ROLLBACK ends the transaction unsuccessfully and cancels all its changes, restoring the data to the state before the transaction. A committed transaction reaches the committed state, whereas a rolled-back transaction reaches the aborted state. Both statements are used to finish a transaction, but with opposite results.
4. What is meant by consistency? Who is responsible for it?
Consistency means that a transaction, when run alone on a consistent database, leaves it consistent, satisfying all integrity constraints and business rules. For example, the total of A and B must not change in a transfer. The DBMS helps by enforcing declared constraints such as primary key, foreign key and CHECK. However, it cannot know every business rule, so the application programmer is primarily responsible for writing transactions that preserve consistency.
5. Explain the partially committed state.
A transaction enters the partially committed state after its last statement has executed. At this point, the changes may still be in main-memory buffers and are not yet guaranteed to be on stable storage. If a failure happens now, the transaction can still move to the failed state and be rolled back. Only after the DBMS has safely recorded the changes (log records on stable storage) does the transaction move to the committed state.
6. Why do DBMSs allow interleaved execution?
Running transactions strictly one by one wastes resources, because while one transaction waits for disk I/O the CPU is idle. Interleaving lets the CPU work on another transaction during that wait, which raises throughput. It also lets short transactions finish quickly instead of waiting behind long ones, which reduces average response time. The price is the risk of interference, so concurrency control is needed to keep the result equal to some serial execution.
7. What is the difference between serial and non-serial schedules?
In a serial schedule, each transaction runs to completion before the next begins, so there is no interleaving. Serial schedules are always correct but give low throughput. In a non-serial schedule, the actions of different transactions are interleaved, which improves resource use and response time. A non-serial schedule is acceptable only if its effect equals that of some serial schedule. Otherwise it may produce inconsistent data.
8. Why can two serial schedules give different results and still both be correct?
Different orders of transactions can change the final values. For example, adding 10% interest before a transfer gives a different final balance than adding it after the transfer. Yet in both cases every transaction ran fully and all integrity constraints hold. The DBMS only promises that concurrent execution equals some serial order, not a specific one, so any such order is regarded as correct.
9. Write the schedule notation with an example.
Actions are written as Ri(X) for Ti reads X, Wi(X) for Ti writes X, and Ci or Ai for commit or abort. For two transactions, a serial schedule is R1(A) W1(A) C1 R2(A) W2(A) C2. An interleaved schedule is R1(A) R2(A) W1(A) W2(A) C1 C2. In both, the order inside each transaction is preserved.
10. What does the DBMS actually see of a transaction?
The DBMS sees only a sequence of read and write operations on database objects, followed by a commit or abort. Computations performed in the application’s memory, such as subtracting 500 from a balance, are not visible to it. Therefore, the DBMS cannot judge the meaning of a transaction. It controls only the order of reads and writes to ensure isolation, and it logs writes to support atomicity and durability.

D. Long Answer Questions (5)

L1. Explain the ACID properties of transactions with suitable examples.
Introduction. A DBMS must keep data correct despite failures and concurrent access. For this, every transaction should satisfy four properties known as ACID.
Atomicity means that all actions of a transaction are done or none are. In a transfer of ₹500 from A to B, the debit and credit must both occur. If a crash occurs in between, the DBMS undoes the partial debit using the log.
Consistency means that a transaction run alone leaves the database consistent. In the same transfer, the sum A + B must stay unchanged and constraints such as non-negative balance must hold. The programmer is mainly responsible, assisted by integrity constraints.
Isolation means that every transaction appears to run alone although the DBMS interleaves them. If two users book the last cinema seat together, isolation ensures only one succeeds. It is implemented by concurrency control such as locking, and the usual correctness target is serializability.
Durability means that committed changes survive crashes. The DBMS writes log records to stable storage before reporting commit, and after a crash it redoes committed changes if needed.
Responsible components: the recovery manager supports atomicity (undo) and durability (redo); concurrency control supports isolation; the programmer plus constraints support consistency (see Figure 1.3).
Conclusion. Together, the four properties make banking, reservation and e-commerce systems reliable.
L2. Describe the states of a transaction with a neat state diagram.
A transaction moves through five states (Figure 1.2).
1. Active: the initial state; the transaction executes its reads and writes.
2. Partially committed: entered after the final statement executes. The changes may still be only in memory buffers.
3. Committed: entered after the DBMS has safely recorded the changes (log forced to stable storage). The effects are permanent, and this is a terminal state.
4. Failed: entered when normal execution cannot go on, because of a logical error, system crash, deadlock or a failure while writing. A transaction can fail from the active or the partially committed state.
5. Aborted: entered after the DBMS has rolled back the transaction and restored the database to its state before the transaction. This is also a terminal state. After this, the system may either restart the transaction (if the cause was a hardware or software failure, not a logical error) or kill it.
Transitions: Active → Partially committed (last statement done); Partially committed → Committed (changes made safe); Active/Partially committed → Failed (error); Failed → Aborted (rollback).
Example: In a UPI payment, the payment is Active during the debit/credit, Partially committed after the last write, and Committed when the bank confirms. If the network fails earlier, it becomes Failed and then Aborted, and the money is returned.
L3. Define schedule. Explain serial, non-serial and complete schedules with examples.
Definition. A schedule is an ordered list of actions (reads, writes, commits, aborts) of a set of transactions, preserving the order of actions inside each transaction.
Notation. Ri(X), Wi(X), Ci, Ai.
Serial schedule. Transactions run one after another with no interleaving. Example: R1(A) W1(A) C1 R2(A) W2(A) C2. It is always correct but gives poor throughput because the CPU idles during I/O waits.
Non-serial (interleaved) schedule. Actions of different transactions are mixed. Example: R1(A) R2(A) W1(A) W2(A) C1 C2. It improves utilisation and response time, but may violate isolation unless it is equivalent to a serial schedule.
Complete schedule. A schedule that has a commit or an abort for every transaction in it.
Number of serial schedules. n transactions have n! serial schedules; for 3 transactions there are 6.
Example of different correct serial results. With A = B = 1000, T1 = transfer 100 from A to B and T2 = add 10% interest to both: T1;T2 gives (990, 1210) and T2;T1 gives (1000, 1200). Both are correct, since the total is 2200 in both cases.
Conclusion. Schedules are the tool to study concurrent execution. Chapter 2 explains how to decide which non-serial schedules are safe.
L4. Explain how a DBMS ensures the ACID properties.
Overview. A DBMS does not use one single mechanism; different components cover different properties.
1. Atomicity and durability: log and recovery manager. Each change is recorded in a log on stable storage, containing identification of the transaction and the old and new values. If a transaction fails or the system crashes before commit, the recovery manager undoes its changes using old values. After commit, the log is forced to stable storage first, so the recovery manager can redo any committed change that did not reach the data pages.
2. Isolation: concurrency control. The lock manager gives a transaction a lock on a data item before it reads or writes it. Conflicting requests must wait. Protocols such as Two-Phase Locking (Chapter 3) ensure that the final result equals a serial execution. Deadlocks that may result are detected and resolved (Chapter 4).
3. Consistency: constraints and programmer. The DBMS enforces declared integrity constraints (primary key, foreign key, CHECK) at the end of statements or transactions and aborts violators. The programmer writes transactions that, when run alone, preserve the application’s rules. Atomicity and isolation then ensure that the rules are preserved even with failures and concurrency.
Summary. Log + recovery for A and D, locking for I, constraints + programmer for C.
L5. Using a funds-transfer example, show what can go wrong if ACID properties are not enforced.
Setting. A = ₹5,000, B = ₹3,000. T1 transfers ₹500 from A to B.
Without atomicity. If the system fails after WRITE(A) but before WRITE(B), A = 4,500 and B = 3,000, so ₹500 vanishes. Total becomes 7,500 instead of 8,000.
Without consistency. If the program mistakenly adds 5,000 instead of 500 to B, the data may satisfy no business rule; the total is wrong although every step ran.
Without isolation. Suppose T2 reads A and B for an audit between T1’s two writes. It sees A = 4,500 and B = 3,000 and reports a total of 7,500, an incorrect report. Or two simultaneous withdrawals from A could both read 5,000 and both write back, causing a lost update.
Without durability. If the bank confirms the transfer and crashes before the data reaches disk, the transfer disappears after restart, although the customer has already been informed.
With ACID. The transfer is all-or-nothing, preserves the total, is invisible to other transactions until complete, and survives failures.
Conclusion. ACID turns a risky sequence of reads and writes into a reliable business operation.

E. Application-Based Questions (5)

AQ1. A UPI app debits ₹2,000 from Ravi but shows “failed” because the receiver’s bank is down. Which property ensures the money returns to Ravi?
Model answer: Atomicity. The debit and the credit are one transaction. Since the credit could not be completed, the transaction fails and the debit is rolled back using the log, so Ravi’s balance is restored.
AQ2. Two users try to book the last seat on a train at the same moment. How do transactions prevent a double booking?
Model answer: Through isolation. Each booking is a transaction that reads the seat count and updates it. The concurrency control ensures the result equals some serial order. The first transaction gets the seat; the second then sees zero seats and fails or is told to choose another train.
AQ3. An ATM dispenses cash, but power fails before the balance update is saved. What should the DBMS guarantee?
Model answer: The cash dispensing and the balance update should be treated as one transaction. If the commit record was not saved, the transaction is undone during recovery (atomicity). If it was committed, the log lets recovery redo the update (durability). Either way, the balance is correct.
AQ4. A university portal updates a student’s marks and the rank list together. Why should these two updates be in one transaction?
Model answer: To keep consistency and atomicity. If marks were updated but the rank list were not, the data would disagree. As one transaction, either both changes are visible or neither, so the database always satisfies the rule that ranks match marks.
AQ5. An online shop reduces stock, creates an order and charges the card. The card charge fails. What should happen?
Model answer: The transaction should fail and be rolled back so that the stock reduction and order record are undone. Atomicity ensures that no order exists without payment and no stock is lost. The customer can retry as a fresh transaction.
PRACTICE TEST

Chapter 1 Assessment (Total 30 marks)

Section A: MCQs (10 × 1 = 10 marks)

1. Which property is violated if a committed transfer disappears after a crash? (A) Atomicity (B) Consistency (C) Isolation (D) Durability
2. Which is a final state of a transaction? (A) Active (B) Failed (C) Committed (D) Partially committed
3. The number of serial schedules for 5 transactions is: (A) 25 (B) 60 (C) 120 (D) 5
4. Which component enforces isolation? (A) Lock manager (B) Log (C) Parser (D) Disk
5. The DBMS “sees” a transaction as a sequence of: (A) SQL joins (B) Reads and writes (C) Indexes (D) Views
6. A schedule with actions of T1 and T2 mixed is: (A) Serial (B) Interleaved (C) Empty (D) Invalid
7. Which command undoes the current transaction? (A) COMMIT (B) ROLLBACK (C) SAVE (D) INSERT
8. UNDO is mainly used for: (A) Isolation (B) Durability (C) Atomicity (D) Indexing
9. REDO is mainly used for: (A) Durability (B) Isolation (C) Parsing (D) Sorting
10. Order of actions inside a transaction in a schedule is: (A) Reversed (B) Preserved (C) Random (D) Deleted

Section B: Short answers (3 × 3 = 9 marks)

11. Define a transaction and name its four properties.
12. What is the difference between a serial and an interleaved schedule?
13. Explain the failed and aborted states.

Section C: Descriptive (2 × 5.5 = 11 marks)

14. Explain ACID properties with a funds-transfer example. (5.5)
15. Draw and explain the transaction state diagram. (5.5)

Answer Key

MCQs: 1-D, 2-C, 3-C (5! = 120), 4-A, 5-B, 6-B, 7-B, 8-C, 9-A, 10-B.
Q11: A transaction is a logical unit of work of reads and writes that is done fully or not at all. Properties: Atomicity, Consistency, Isolation, Durability.
Q12: In a serial schedule, transactions run one after another with no mixing. In an interleaved schedule, their actions are mixed; it gives better throughput but must be equivalent to a serial schedule to be correct.
Q13: Failed: normal execution cannot continue (error, crash, deadlock). Aborted: the transaction has been rolled back and the database restored to its earlier state; the transaction may be restarted or killed.
Q14: See L1 (definition of each property, transfer example, responsible component). Award marks: 1 per property with example, 1.5 for diagram/component table.
Q15: See L2 and Figure 1.2 (five states, transitions, example). Award 2 marks for correct diagram, 3.5 for explanation.
CHAPTER SUMMARY

Quick Revision: Chapter 1

Important Concepts
  • A transaction is a logical unit of work: all steps or none; it ends with commit or abort.
  • States: Active → Partially committed → Committed, or Active/Partially committed → Failed → Aborted.
  • ACID = Atomicity, Consistency, Isolation, Durability.
  • Atomicity and durability: recovery manager with log (undo and redo). Isolation: concurrency control. Consistency: programmer and constraints.
  • A schedule is an ordered list of actions of several transactions; order inside each transaction is preserved.
  • Serial: no interleaving. Non-serial: interleaved. Complete: every transaction has commit or abort.
  • n transactions have n! serial schedules; different serial orders may give different but correct results.
Key DefinitionsTransaction, Atomicity, Consistency, Isolation, Durability and Schedule are defined in sections 1.2, 1.4 and 1.6. Learn each in one line.
Five Most Important Examination Questions 1. Explain ACID properties with examples.
2. Draw and explain the transaction state diagram.
3. Define schedule; differentiate serial and non-serial schedules.
4. How does a DBMS ensure atomicity and durability?
5. Show with an example what can go wrong without isolation or atomicity.

Next: Chapter 2 – Concurrent Execution, Serializability and Recoverability

EDUKOSAL • www.edukosal.com • UG DBMS • Transaction Management • Chapter 1 • © EDUKOSAL. For learning use.
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
EDUKOSAL

Transaction Management

Database Management Systems • UG Study Notes

CHAPTER 2 OF 5 • READ-ONLY EDITION

www.edukosal.com

Book Plan

  1. Chapter 1 – Transactions, ACID Properties and Schedules
  2. Chapter 2 – Concurrent Execution, Serializability and Recoverability (this post)
  3. Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management, Performance of Locking
  4. Chapter 4 – Dealing with Deadlocks
  5. Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery

Inside Chapter 2: 2.1 Concurrent execution • 2.2 Anomalies (WR, RW, WW) • 2.3 Conflicts and conflict equivalence • 2.4 Serializability and precedence graph • 2.5 View serializability (introduction) • 2.6 Recoverability • 2.7 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary

EDUKOSAL • UG DBMSUnit: Transaction ManagementChapter 2
CHAPTER 2

Concurrent Execution, Serializability and Recoverability

Learning Outcomes After this chapter you will be able to: explain why DBMSs run transactions concurrently; identify the anomalies caused by interleaving (dirty read, unrepeatable read, lost update); define conflicting operations and conflict equivalence; test conflict serializability with a precedence graph; and classify schedules as recoverable, cascadeless (ACA) or strict.

2.1 Concurrent Execution of Transactions

In Chapter 1 you saw that running transactions one by one (a serial schedule) is always correct but slow. A bank server may receive thousands of requests every second. If each had to wait for the previous one to finish, customers would queue endlessly. So a DBMS lets transactions overlap in time. This is called concurrent execution, and the resulting schedule is an interleaved (non-serial) schedule.

Why concurrency?

  • Better throughput and resource use: A transaction spends much time waiting for disk I/O. While it waits, the CPU can run another transaction, so more transactions are finished per second.
  • Lower average response time: A short transaction (checking a balance) need not wait behind a long one (monthly interest calculation).

Everyday analogy: A single cashier at a railway counter serving one passenger from start to end is a serial schedule. Several counters serving different passengers while sharing one ticket register is concurrency; it is faster, but the shared register must be updated carefully.

The ProblemInterleaving is useful, but it can make transactions interfere. The goal of concurrency control is to allow interleaving while keeping the result equivalent to some serial execution (the Isolation property).

2.2 Anomalies Due to Interleaved Execution

Problems arise only when two transactions touch the same data item and at least one of them writes. Three standard patterns of conflict are named by the order of the two actions.

WR: Dirty Read T1: W(A)T2: R(A) (T1 not committed)T1: Abort T2 has read a value thatnever officially existed. RW: Unrepeatable Read T1: R(A) = 10T2: W(A) = 9, CommitT1: R(A) = 9 T1 reads the same item twiceand gets different values. WW: Lost Update T1: R(A), T2: R(A)T1: W(A)T2: W(A) overwrites T1 One transaction’s updatedisappears.
Figure 2.1: The three classic anomalies caused by conflicting actions.
ConflictAnomaly nameWhat goes wrongEveryday example
WR (write then read)Dirty read (reading uncommitted data)T2 reads a value written by T1 that may later be rolled back.You see a “credited” SMS balance that the bank later reverses.
RW (read then write)Unrepeatable readT1 reads A twice and finds that its value changed in between.A shopping page shows 10 items in stock, but 9 at checkout.
WW (write then write)Overwriting uncommitted data / lost updateT2 overwrites a value of T1 before T1 commits, losing T1’s update.Two clerks edit the same Excel cell; the later save wins.

Example 1: Basic Example (Lost Update)

Problem / Situation: Stock of an item A = 100. T1 adds 50 units; T2 adds 20 units. Correct final stock: 170.
Explanation: Both transactions read the old value before either writes.
Step-by-step solution:
StepT1T2A in DB
1R(A) → 100100
2R(A) → 100100
3W(A) = 100 + 50 = 150, Commit150
4W(A) = 100 + 20 = 120, Commit120
Final result: A = 120 instead of 170. T1’s update of +50 is lost. Any serial order gives 170, so this interleaving is not acceptable.

Example 2: Real-Life Application (Dirty Read)

Real-world situation: A = 1000, B = 1000. T1 transfers ₹100 from A to B. T2 credits 6% interest to both accounts.
How the concept is applied: Schedule S: R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1. T2 reads A after T1 has written it but before T1 commits (WR conflict), and T1 reads B after T2 has written it (another WR).
ExecutionFinal AFinal BA + B
Serial T1; T295411662120
Serial T2; T196011602120
Interleaved S95411602114
Calculation for S: A = 900 × 1.06 = 954. B = 1000 × 1.06 = 1060; then T1 adds 100: B = 1160.
Learning outcome: The interleaved result (954, 1160) equals neither serial result; ₹6 of interest has been lost. S is therefore not serializable.

2.3 Conflicts and Conflict Equivalence

Definition: Conflicting actionsTwo actions conflict if they (1) belong to different transactions, (2) operate on the same data item, and (3) at least one is a write.
PairConflict?Reason
R1(A), R2(A)NoBoth only read; order does not matter.
R1(A), W2(A)Yes (RW)Order changes what T1 reads.
W1(A), R2(A)Yes (WR)Order changes what T2 reads.
W1(A), W2(A)Yes (WW)Order decides the final value of A.
W1(A), W2(B)NoDifferent data items.
R1(A), W1(A)NoSame transaction.
Definition: Conflict equivalent schedulesTwo schedules are conflict equivalent if they involve the same actions of the same transactions and every pair of conflicting actions is ordered in the same way in both. Non-conflicting actions may be swapped freely.

2.4 Serializability

Definition: Conflict serializable scheduleA schedule is conflict serializable if it is conflict equivalent to some serial schedule. Such a schedule gives the same effect as a serial execution, so it satisfies the Isolation property.

When we judge a schedule, we consider only the committed transactions; aborted transactions are treated as if they never occurred (their effects are undone).

Working process: testing with a precedence graph

  1. Draw one node for each (committed) transaction.
  2. For every pair of conflicting actions where Ti’s action comes first and Tj’s later, draw a directed edge Ti → Tj.
  3. If the graph has a cycle, the schedule is not conflict serializable.
  4. If the graph is acyclic, the schedule is conflict serializable. A topological order of the nodes gives an equivalent serial schedule.
Schedule S1: acyclic R1(A) W1(A) R2(A) W2(A) R1(B) W1(B) R2(B) W2(B) T1 T2 on A and B Conflict serializableEquivalent serial order: T1, T2 Schedule S2: cycle R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) R1(B) W1(B) T1 T2 on A on B Not conflict serializableT1 → T2 and T2 → T1 form a cycle
Figure 2.2: Precedence graphs for a serializable and a non-serializable schedule.

Example 3: Practical / Case Study (Precedence graph)

Background: Three transactions run on items X and Y with schedule S3: R1(X) W2(X) R3(Y) W1(Y) R3(X) Commit all.
Problem: Is S3 conflict serializable? If so, give an equivalent serial order.
Application of the concept: List conflicting pairs.
  • On X: R1(X) before W2(X) gives T1 → T2. W2(X) before R3(X) gives T2 → T3.
  • On Y: R3(Y) before W1(Y) gives T3 → T1.
Edges: T1 → T2, T2 → T3, T3 → T1. These form the cycle T1 → T2 → T3 → T1.
Result: The graph has a cycle.
Conclusion: S3 is not conflict serializable. If R3(Y) had come after W1(Y), the edge T3 → T1 would become T1 → T3 and the graph would be acyclic, giving serial order T1, T2, T3.
Exam TipMark all conflicting pairs item by item (all of X, then all of Y). Do not compare actions of the same transaction, and do not draw an edge for two reads.

2.5 View Serializability (Introduction)

Conflict serializability is sufficient but sometimes too strict. View serializability is a weaker (more general) condition. Two schedules are view equivalent if (1) each transaction reads the same values (from the same writer, or the initial value) in both, and (2) the final write on each data item is by the same transaction. A schedule is view serializable if it is view equivalent to some serial schedule.

BasisConflict serializabilityView serializability
ScopeNarrowerBroader (includes all conflict serializable schedules)
TestingEasy: cycle test on the precedence graphHard (testing is NP-complete)
Use in DBMSUsed in practiceMainly theoretical; allows “blind writes”
Remember ThisEvery conflict serializable schedule is view serializable, but not the reverse. DBMSs therefore enforce conflict serializability, usually through locking protocols (Chapter 3).

2.6 Recoverability

Serializability considers only schedules where all transactions commit. But transactions can also abort. If T2 has used values written by T1 and then T1 aborts, T2’s work is based on data that never officially existed. The schedule must be arranged so that failures can be handled safely. This is the study of recoverability.

Reads-fromTransaction T2 reads from T1 if T1 writes a data item and T2 later reads that value (before T1 has finished).

Classes of schedules

ClassDefinitionExample
RecoverableEach transaction commits only after all transactions it has read from have committed.W1(A) R2(A) C1 C2
Non-recoverableA transaction commits before a transaction it read from. If the latter aborts, the commit cannot be undone.W1(A) R2(A) C2 Abort1
Avoids cascading aborts (ACA / cascadeless)Transactions read only values written by committed transactions. No dirty reads.W1(A) C1 R2(A) C2
StrictNo transaction reads or overwrites an item written by another transaction until that transaction commits or aborts.W1(A) C1 W2(A) C2
All schedules Recoverable schedules Cascadeless (ACA) schedules Strict schedules Strict 2PL produces schedules here (also conflict serializable, see Chapter 3)
Figure 2.3: Strict ⊂ Cascadeless ⊂ Recoverable ⊂ All schedules.

Cascading rollback

If T2 has read an uncommitted value of T1 and T1 aborts, T2 must also be aborted. If T3 read from T2, then T3 must be aborted too, and so on. This chain of aborts is a cascading rollback. It wastes work, so DBMSs prefer cascadeless or strict schedules.

Worked Example: Classify schedules

ScheduleAnalysisClass
S4: W1(A) R2(A) C2 Abort1T2 read from T1 and committed before T1 ended. T1 aborts, but T2’s commit cannot be undone.Non-recoverable
S5: W1(A) R2(A) C1 C2T2 commits after T1. But T2 read uncommitted data; if T1 had aborted, T2 would also have to abort.Recoverable, not cascadeless
S6: W1(A) C1 R2(A) W2(A) C2T2 reads and writes A only after T1 has committed, so there is no dirty read and no overwrite of uncommitted data.Strict
S7: W1(A) W2(A) C1 C2T2 overwrites A before T1 commits (no reads, so cascadeless), but not strict.Cascadeless, not strict
Key Point: Serializability vs RecoverabilityThe two ideas are independent. A schedule can be serializable but non-recoverable (S4: the committed projection contains only T2, which is trivially serializable), or recoverable but not serializable (R1(A) R2(A) W1(A) W2(A) C1 C2). A good DBMS needs both.

2.7 Applications, Advantages and Limitations

Applications

  • Banking and payments: thousands of UPI and ATM transactions run concurrently while every balance stays correct.
  • Railway/airline booking: concurrent users, but one seat is sold once.
  • E-commerce: stock counts are updated by many buyers at once without lost updates.
  • Database design and testing: serializability tests are used by researchers and DBMS designers to prove that a concurrency protocol is correct.
AdvantagesLimitations
Concurrency raises throughput and lowers response time.
Serializability gives a clear, mathematical correctness rule.
Recoverability makes safe handling of aborts possible.
The precedence-graph test is simple.
Testing a finished schedule is not practical in real time; DBMSs enforce protocols (locking) instead.
Strict schedules reduce concurrency.
Cascading rollbacks waste work.
View serializability is hard to test.

Important Points for Revision

Key Terminology Conflict – different transactions, same item, at least one write. Dirty read – reading uncommitted data. Lost update – overwritten update. Precedence graph – directed graph of conflict order. Cascading rollback – chain of aborts. Reads-from – T2 reads a value written by T1.
Exam TipsAlways state the three conditions of a conflict. In a serializability question, show the list of edges, the graph and the conclusion (acyclic: give the serial order). For recoverability questions, check the commit order of the transactions involved.
Common MistakesDrawing an edge for R–R pairs. Forgetting that a cycle means NOT serializable. Believing that serializable schedules are automatically recoverable. Confusing cascadeless (no dirty reads) with strict (no dirty reads and no overwrites of uncommitted data).

Difference Between Important Concepts

BasisRecoverableCascadelessStrict
Dirty readsAllowed if commit order is rightNot allowedNot allowed
Overwrite of uncommitted dataAllowedAllowedNot allowed
Cascading abortsPossibleNoneNone
Undo during rollbackComplexComplexSimple (restore before-image)
BasisSerial scheduleSerializable schedule
InterleavingNonePresent
Equivalent to a serial scheduleIt is oneYes
ConcurrencyNoneHigh
QUESTION BANK

Chapter 2: Questions with Answers

A. Multiple Choice Questions (20)

Q1. Concurrent execution is allowed mainly to:
A. Improve throughput and reduce response time
B. Increase disk size
C. Remove the need for a log
D. Avoid using locks
Answer: A. Overlapping transactions keeps the CPU busy during I/O waits and lets short transactions finish early.
Q2. A WR conflict leads to:
A. Lost update
B. Unrepeatable read
C. Dirty read
D. Phantom deadlock
Answer: C. T2 reads data written by T1 before T1 commits.
Q3. An RW conflict causes:
A. Dirty read
B. Unrepeatable read
C. Cascading rollback
D. Durability failure
Answer: B. T1 reads an item, T2 changes it, and T1’s second read returns a different value.
Q4. A WW conflict can cause:
A. Dirty read only
B. Atomicity failure only
C. A syntax error
D. Overwriting of uncommitted data (lost update)
Answer: D. The later write replaces the earlier one before the first transaction commits.
Q5. Two actions conflict when they:
A. Belong to different transactions, access the same item and at least one is a write
B. Belong to the same transaction
C. Are both reads of the same item
D. Access different items
Answer: A. All three conditions must hold.
Q6. Which pair of actions does NOT conflict?
A. W1(A), R2(A)
B. R1(A), R2(A)
C. R1(A), W2(A)
D. W1(A), W2(A)
Answer: B. Two reads never conflict.
Q7. A schedule is conflict serializable if and only if its precedence graph is:
A. Complete
B. Empty
C. Acyclic
D. Cyclic
Answer: C. A cycle means no serial order can respect all conflicts.
Q8. The nodes of a precedence graph represent:
A. Transactions
B. Data items
C. Locks
D. Disk blocks
Answer: A. One node per (committed) transaction.
Q9. An edge Ti → Tj is drawn when:
A. Ti commits after Tj
B. A conflicting action of Ti precedes a conflicting action of Tj
C. Ti and Tj both read the same item
D. Ti starts after Tj
Answer: B. The edge shows that Ti must come before Tj in an equivalent serial order.
Q10. A precedence graph has edges T1 → T2 and T2 → T1. The schedule is:
A. Not conflict serializable
B. Conflict serializable
C. Serial
D. Strict
Answer: A. The two edges form a cycle.
Q11. A graph has edges T1 → T3 and T3 → T2 (no others). An equivalent serial order is:
A. T2, T1, T3
B. T3, T1, T2
C. T1, T3, T2
D. T2, T3, T1
Answer: C. A topological order respects both edges.
Q12. A recoverable schedule requires that a transaction commits:
A. Before any other transaction
B. Immediately after it reads
C. Only once the DBMS restarts
D. After all transactions it read from have committed
Answer: D. Otherwise a committed transaction could depend on data that is later rolled back.
Q13. Cascading rollback means:
A. Rolling back only the oldest transaction
B. Abort of one transaction forcing the abort of others that read its data
C. Rolling back a committed transaction
D. Deleting the log
Answer: B. Dependent transactions must be undone in a chain.
Q14. A cascadeless (ACA) schedule allows transactions to read:
A. Only values written by committed transactions
B. Any value
C. Only the initial values
D. No values
Answer: A. This eliminates dirty reads and therefore cascading aborts.
Q15. In a strict schedule, a transaction may not read or write an item until the last writer has:
A. Started
B. Read it
C. Committed or aborted
D. Locked another item
Answer: C. This also makes rollback simple.
Q16. Which relation among schedule classes is correct?
A. Recoverable ⊂ Strict
B. Strict ⊂ Cascadeless ⊂ Recoverable
C. Cascadeless ⊂ Strict
D. Recoverable ⊂ Cascadeless
Answer: B. Each stronger class is a subset of the weaker one.
Q17. The schedule W1(A) R2(A) C2 Abort1 is:
A. Strict
B. Cascadeless
C. Recoverable
D. Non-recoverable
Answer: D. T2 read from T1 but committed before T1.
Q18. Which locking protocol (Chapter 3) produces conflict serializable and strict schedules?
A. Strict 2PL
B. No locking
C. Releasing locks after every read
D. Timestamps only
Answer: A. Strict 2PL holds exclusive locks until commit or abort.
Q19. Two schedules are conflict equivalent if:
A. They have the same number of transactions
B. They have the same actions and all conflicting pairs are in the same order
C. They give different final states
D. They are both serial
Answer: B. Only the order of conflicting actions matters.
Q20. Which statement about view serializability is true?
A. It is narrower than conflict serializability
B. It is easy to test in polynomial time
C. It is unrelated to serial schedules
D. Every conflict serializable schedule is view serializable
Answer: D. View serializability is a broader class.

B. Very Short Answer Questions (10)

1. Why is concurrent execution used?
It improves throughput by using the CPU while other transactions wait for I/O. It also reduces the average response time of short transactions.
2. What is a dirty read?
A dirty read happens when a transaction reads a value written by another transaction that has not yet committed. If the writer aborts, the value never existed officially.
3. What is a lost update?
A lost update occurs when two transactions read the same value and both write back, so one transaction’s update is overwritten. The final value reflects only one of the updates.
4. When do two actions conflict?
They conflict if they belong to different transactions, access the same data item, and at least one is a write.
5. What is a precedence graph?
It is a directed graph with transactions as nodes and an edge Ti → Tj whenever a conflicting action of Ti precedes one of Tj. It is used to test conflict serializability.
6. When is a schedule conflict serializable?
When it is conflict equivalent to some serial schedule, which happens exactly when its precedence graph has no cycle.
7. Define a recoverable schedule.
A schedule is recoverable if every transaction commits only after all transactions it has read from have committed.
8. What is cascading rollback?
When one transaction aborts, every transaction that read its uncommitted data must also abort, and so on down the chain.
9. What is a strict schedule?
It is a schedule in which no transaction reads or overwrites an item written by another transaction until that writer commits or aborts.
10. Are all serializable schedules recoverable?
No. Serializability and recoverability are independent. A serializable schedule may commit a transaction before the one it read from, making it non-recoverable.

C. Short Answer Questions (10)

1. Explain the WR conflict with an example.
In a WR conflict, T1 writes a data item and T2 reads it before T1 commits, so T2 sees uncommitted data (dirty read). For example, T1 debits ₹100 from A and T2 reads the reduced balance to add interest. If T1 then aborts, T2 has used a value that never officially existed and its results are wrong. The anomaly breaks isolation and may require T2 to abort as well.
2. Explain the unrepeatable read.
An unrepeatable read arises from an RW conflict. T1 reads an item, T2 then modifies it and commits, and T1 reads it again and finds a different value. For example, T1 reads the stock as 10, T2 sells one unit, and T1 reads it again as 9. A transaction in isolation would see the same value both times, so this interleaving violates isolation.
3. Differentiate conflict equivalence from view equivalence.
Conflict equivalent schedules order every pair of conflicting actions identically. View equivalent schedules need only the same reads-from relationships (each transaction reads from the same writer) and the same final writes. View equivalence is therefore weaker and covers more schedules, but it is hard to test, whereas conflict equivalence is tested easily with a precedence graph.
4. How is a serial order obtained from a precedence graph?
If the graph is acyclic, a topological sort gives the order. Repeatedly pick a node with no incoming edges, place it next in the serial order, and remove it with its outgoing edges. Continue until all nodes are placed. Every edge Ti → Tj then has Ti before Tj, so the serial schedule is conflict equivalent to the original schedule.
5. Why can a schedule be serializable yet unacceptable?
Serializability ignores aborts. Take W1(A) R2(A) C2 Abort1. Looking only at committed transactions it appears fine, but T1 aborts after T2 has committed with T1’s uncommitted data. Such a schedule is non-recoverable and cannot be rolled back safely. A practical schedule must be both serializable and recoverable.
6. Explain recoverable schedules.
A schedule is recoverable if each transaction commits only after every transaction whose changes it read has committed. This ensures that a committed transaction never depends on data that might later be rolled back. For example, W1(A) R2(A) C1 C2 is recoverable, but W1(A) R2(A) C2 Abort1 is not, because T2 committed on data from T1 which aborted.
7. What are cascadeless schedules? Why are they preferred?
In a cascadeless (ACA) schedule, transactions read only values written by committed transactions. Hence no dirty reads occur and aborting one transaction never forces others to abort. They are preferred because cascading rollbacks waste completed work and complicate recovery. Every cascadeless schedule is recoverable, but a recoverable schedule need not be cascadeless.
8. How does a strict schedule differ from a cascadeless schedule?
A cascadeless schedule forbids reading uncommitted data. A strict schedule additionally forbids overwriting data written by an uncommitted transaction. Thus W1(A) W2(A) C1 C2 is cascadeless but not strict. Strict schedules make rollback simple, because the system can just restore the before-image of each item written by the aborted transaction.
9. State the conflict-serializability test.
Build the precedence graph of the committed transactions. Add an edge Ti → Tj for each pair of conflicting actions in which Ti’s action comes first. If the graph contains a cycle, the schedule is not conflict serializable. If it is acyclic, the schedule is conflict serializable, and any topological order of the graph is an equivalent serial schedule.
10. Why does a DBMS use protocols instead of testing schedules?
A schedule can only be tested after it has happened, when it is too late to repair it. Moreover, transactions arrive continuously and the whole schedule is not known in advance. A DBMS therefore uses protocols, such as Strict Two-Phase Locking, that guarantee only serializable and recoverable schedules can occur, rather than checking each finished schedule.

D. Long Answer Questions (5)

L1. Explain the problems (anomalies) caused by concurrent execution of transactions with examples.
Introduction. Concurrent execution improves throughput but, when transactions access the same data, their interleaving can corrupt data. Anomalies are classified by the order of the conflicting actions (Figure 2.1).
1. WR conflict (dirty read). T1 writes A, and T2 reads A before T1 commits. If T1 later aborts, T2 has used invalid data. Example: with A = B = 1000, T1 transfers 100 from A to B and T2 adds 6% interest to both. In the schedule R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1, the final state is A = 954, B = 1160, which differs from both serial results (954, 1166) and (960, 1160). Interest of ₹6 is lost.
2. RW conflict (unrepeatable read). T1 reads A, T2 modifies A and commits, T1 reads A again and sees a different value. Example: stock changes from 10 to 9 between two reads.
3. WW conflict (lost update / overwriting uncommitted data). Two transactions read A = 100; T1 writes 150 and T2 writes 120. The final value 120 loses T1’s +50.
Consequences. Wrong results, inconsistent totals and possible cascading aborts.
Conclusion. Concurrency control must prevent these interleavings so that the final effect equals a serial execution.
L2. Explain conflict serializability and the precedence graph test with an example.
Conflicting actions. Two actions conflict if they belong to different transactions, access the same item and at least one is a write. Types: RW, WR, WW.
Conflict equivalence. Two schedules are conflict equivalent if they contain the same actions and order each conflicting pair identically. A schedule is conflict serializable if it is conflict equivalent to some serial schedule.
Test. (1) Make a node for each committed transaction. (2) For each conflicting pair with Ti first and Tj later, draw an edge Ti → Tj. (3) If the graph has a cycle, the schedule is not conflict serializable; otherwise it is, and a topological sort gives an equivalent serial order.
Example. S1: R1(A) W1(A) R2(A) W2(A) R1(B) W1(B) R2(B) W2(B). On A, T1’s actions precede T2’s conflicting actions, so T1 → T2. On B, again T1 → T2. The graph has one edge and no cycle, so S1 is conflict serializable and equivalent to T1;T2.
Now S2: R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) R1(B) W1(B). On A: T1 → T2. On B: T2’s actions precede T1’s, so T2 → T1. The cycle T1 → T2 → T1 shows S2 is not conflict serializable (Figure 2.2).
Conclusion. The test is easy, and conflict serializability is the correctness criterion used by real DBMSs.
L3. Discuss recoverable, cascadeless and strict schedules with examples and their relationship.
Need. Serializability does not consider aborts. If T2 reads data written by an uncommitted T1 and T1 aborts, the system must be able to recover.
Recoverable. Every transaction commits only after all transactions it read from have committed. Example: W1(A) R2(A) C1 C2 (recoverable); W1(A) R2(A) C2 Abort1 (non-recoverable, since T2 has committed on rolled-back data).
Avoiding cascading aborts (cascadeless). Transactions read only committed values. Example: W1(A) C1 R2(A) C2. In W1(A) R2(A) C1 C2, if T1 aborted, T2 would have to abort too; that is a cascading rollback, so this schedule is recoverable but not cascadeless.
Strict. No transaction reads or overwrites an item until the last writer has committed or aborted. Example: W1(A) C1 W2(A) C2. Compare W1(A) W2(A) C1 C2, which is cascadeless but not strict. Strict schedules allow simple rollback by restoring before-images.
Relationship. Strict ⊂ Cascadeless ⊂ Recoverable ⊂ All schedules (Figure 2.3).
Conclusion. A DBMS should produce schedules that are serializable and, preferably, strict. Strict Two-Phase Locking achieves this.
L4. Show that a schedule that is not conflict serializable can produce a wrong result. Use a numerical example.
Setting. A = 1000, B = 1000. T1 transfers ₹100 from A to B. T2 adds 6% interest to A and B. Consistency requires the total after the transactions to equal that of a serial execution.
Serial executions. T1;T2: A = 900 × 1.06 = 954, B = 1100 × 1.06 = 1166, total 2120. T2;T1: A = 1060 − 100 = 960, B = 1060 + 100 = 1160, total 2120. Both are valid.
Interleaved schedule S. R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1. T1 writes A = 900. T2 reads A = 900 and writes 954. T2 reads B = 1000 and writes 1060, and commits. T1 reads B = 1060 and writes 1160. Final: A = 954, B = 1160, total 2114.
Analysis. The result matches neither serial result, and ₹6 of interest has been lost. In the precedence graph, A gives T1 → T2 and B gives T2 → T1: a cycle.
Conclusion. A non-serializable schedule violates isolation and can corrupt data, so the DBMS must prevent it, for example by locking.
L5. Compare serializability and recoverability. Why does a DBMS need both?
Serializability deals with the correctness of the interleaving of committed transactions: the result must equal some serial execution. It supports the Isolation property and is tested by the precedence graph.
Recoverability deals with the safety of aborts and commits: no transaction may commit on data that is later rolled back. It supports Atomicity and Durability by making recovery possible.
Independence. A schedule can be serializable but non-recoverable, e.g. W1(A) R2(A) C2 Abort1, whose committed projection (only T2) is trivially serializable, yet T2 committed on data from the aborted T1. A schedule can also be recoverable but not serializable, e.g. R1(A) R2(A) W1(A) W2(A) C1 C2: there is no reads-from, so it is recoverable, but the edges T1 → T2 and T2 → T1 form a cycle.
Table.
BasisSerializabilityRecoverability
ConcernsOrder of conflicting actionsOrder of commits vs reads-from
Failure when violatedWrong resultsUnrecoverable commits, cascading aborts
TestPrecedence graphCheck commit order
Need for both. A DBMS must produce results that are correct under concurrency and still recoverable after failures. Strict 2PL guarantees both.

E. Application-Based Questions (5)

AQ1. Two clerks update the same student’s fee record simultaneously; one update vanishes. Name the anomaly and the cause.
Model answer: Lost update (WW conflict). Both read the old value and wrote back results based on it, so the second write overwrote the first. Concurrency control (locking) should force one to wait.
AQ2. A report shows the stock as 10 and, on refresh within the same transaction, as 8. What went wrong, and which isolation requirement is violated?
Model answer: Unrepeatable read (RW conflict). Another transaction updated and committed the stock in between. A transaction in isolation should read the same value both times.
AQ3. Schedule: R1(X) W1(X) R2(X) W2(X) R2(Y) W2(Y) R1(Y) W1(Y). Is it conflict serializable?
Model answer: On X: T1 → T2. On Y: R2(Y), W2(Y) come before R1(Y), W1(Y), so T2 → T1. The graph has a cycle, so it is not conflict serializable.
AQ4. A payment gateway shows “received” to a merchant based on a payment that is later rolled back. Which schedule property is missing?
Model answer: Cascadeless/recoverable behaviour. The merchant’s transaction read uncommitted data (dirty read). A cascadeless schedule would allow reads only after the payment commits.
AQ5. Classify W1(A) W2(A) C1 C2 and suggest how to make it strict.
Model answer: It has no reads, so it is cascadeless and recoverable, but it is not strict since T2 overwrites A before T1 commits. To make it strict, T2’s write must wait until T1 commits or aborts, for example with an exclusive lock held until the end of T1 (Strict 2PL).
PRACTICE TEST

Chapter 2 Assessment (Total 30 marks)

Section A: MCQs (10 × 1 = 10 marks)

1. Reading uncommitted data is called: (A) Lost update (B) Dirty read (C) Phantom (D) Deadlock
2. Which pair conflicts? (A) R1(A), R2(B) (B) R1(A), R2(A) (C) W1(B), R2(B) (D) W1(A), W1(B)
3. A cycle in the precedence graph means: (A) Serializable (B) Not conflict serializable (C) Strict (D) Serial
4. A recoverable schedule needs commit after: (A) Reads-from transactions commit (B) System restart (C) Log flush only (D) Any abort
5. Strict ⊂ ? ⊂ Recoverable. The missing class is: (A) Serial (B) Cascadeless (C) View (D) Lock
6. Edges T1 → T2, T2 → T3. A serial order is: (A) T3, T2, T1 (B) T2, T1, T3 (C) T1, T2, T3 (D) T3, T1, T2
7. Lost update corresponds to: (A) WW (B) RR (C) WR only (D) No conflict
8. A cascadeless schedule never has: (A) Commits (B) Writes (C) Dirty reads (D) Reads
9. Testing view serializability is: (A) Trivial (B) NP-complete (C) Linear (D) Impossible
10. Which gives strict schedules? (A) Strict 2PL (B) No protocol (C) Dirty reads (D) Random order

Section B: Short answers (3 × 3 = 9 marks)

11. List the three conditions for two actions to conflict.
12. What is a cascading rollback? Give a schedule.
13. State the difference between a cascadeless and a strict schedule.

Section C: Descriptive (2 × 5.5 = 11 marks)

14. For S: R1(A) R2(A) W2(A) W1(A) R3(A) W3(A), draw the precedence graph and decide whether it is conflict serializable. (5.5)
15. Explain recoverable, cascadeless and strict schedules with one example each. (5.5)

Answer Key

MCQs: 1-B, 2-C, 3-B, 4-A, 5-B, 6-C, 7-A, 8-C, 9-B, 10-A.
Q11: Different transactions; same data item; at least one is a write.
Q12: When an abort of one transaction forces others that read its data to abort. Example: W1(A) R2(A) W2(B) R3(B) Abort1 → T2 aborts, then T3 aborts.
Q13: Cascadeless forbids reading uncommitted data. Strict also forbids overwriting uncommitted data.
Q14: Conflicts on A: R1(A) before W2(A): T1 → T2. R2(A) before W1(A): T2 → T1. This is already a cycle, so S is not conflict serializable. (Also W2(A) before W1(A): T2 → T1; W1(A) before R3(A) and W3(A): T1 → T3; T2 → T3.) Award 3 marks for correct edges and graph, 2.5 for conclusion with cycle.
Q15: See L3: recoverable W1(A) R2(A) C1 C2; cascadeless W1(A) C1 R2(A) C2; strict W1(A) C1 W2(A) C2. Award 1 mark per definition+example, 2.5 for relationship and discussion.
CHAPTER SUMMARY

Quick Revision: Chapter 2

Important Concepts
  • Concurrency improves throughput and response time but can cause anomalies: dirty read (WR), unrepeatable read (RW), lost update (WW).
  • Conflict: different transactions, same item, at least one write.
  • Conflict serializable: conflict equivalent to some serial schedule; test: precedence graph has no cycle; topological order gives the serial schedule.
  • View serializability is broader but hard to test; every conflict serializable schedule is view serializable.
  • Recoverable: commit only after reads-from transactions commit. Cascadeless: read only committed data. Strict: no read or overwrite of uncommitted data.
  • Strict ⊂ Cascadeless ⊂ Recoverable. Serializability and recoverability are independent; a DBMS needs both.
Five Most Important Examination Questions 1. Explain concurrency anomalies with examples.
2. Define conflict serializability and explain the precedence-graph test.
3. Explain recoverable, cascadeless and strict schedules and their relationship.
4. Differentiate conflict and view serializability.
5. Test a given schedule for conflict serializability and recoverability.

Next: Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking

EDUKOSAL • www.edukosal.com • UG DBMS • Transaction Management • Chapter 2 • © EDUKOSAL. For learning use.
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
EDUKOSAL

Transaction Management

Database Management Systems • UG Study Notes

CHAPTER 3 OF 5 • READ-ONLY EDITION

www.edukosal.com

Book Plan

  1. Chapter 1 – Transactions, ACID Properties and Schedules
  2. Chapter 2 – Concurrent Execution, Serializability and Recoverability
  3. Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking (this post)
  4. Chapter 4 – Dealing with Deadlocks
  5. Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery

Inside Chapter 3: 3.1 Lock-based concurrency control • 3.2 Strict 2PL • 3.3 Two-Phase Locking (2PL) • 3.4 Introduction to lock management • 3.5 Performance of locking • 3.6 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary

EDUKOSAL • UG DBMSUnit: Transaction ManagementChapter 3
CHAPTER 3

Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking

Learning Outcomes After this chapter you will be able to: explain shared and exclusive locks and their compatibility; state the rules of Strict 2PL and basic 2PL; explain why 2PL gives conflict serializability; describe how a lock manager works (lock table, transaction table, queues, upgrades, latches); and explain blocking, thrashing and ways of improving locking performance.

3.1 Lock-Based Concurrency Control

In Chapter 2 you learned that interleaved schedules must be conflict serializable and recoverable. But a DBMS cannot wait to check a schedule after it has happened; it must prevent bad schedules while transactions run. The most widely used method is locking.

Everyday analogy: When you use a library reading room, you may share a book with others who only want to read it, but if someone wants to write notes in a master copy, nobody else may touch it until the writer finishes. A lock works like this “permission token” on a data item.

Definition: LockA lock is a mechanism that a transaction must obtain on a data object (database, table, page or record) before accessing it. A locking protocol is a set of rules that every transaction must follow when requesting and releasing locks.

Types of locks

LockAlso calledAllowsTaken for
Shared lock (S)Read lockReading the object. Many transactions may hold S on the same object together.READ(A)
Exclusive lock (X)Write lockReading and writing. Only one transaction can hold X, and no other lock can coexist with it.WRITE(A)

Lock compatibility matrix

Held by T1 ↓ / Requested by T2 →SX
SGrantedWait
XWaitWait

This table mirrors the idea of conflicts from Chapter 2: two reads do not conflict, but a write conflicts with both reads and writes. A transaction whose request cannot be granted is blocked (put in a queue) until the conflicting lock is released.

Remember ThisLocks are of two basic modes: S (shared) for reading and X (exclusive) for writing. Only S–S is compatible.

Example 1: Basic Example

Problem / Situation: T1 and T2 only read item A; T3 wants to update A.
Explanation: S locks are compatible with each other but not with X.
Step-by-step solution:
StepActionLock table for A
1T1 requests S(A), granted, reads AHeld: S by T1
2T2 requests S(A), granted, reads AHeld: S by T1, T2
3T3 requests X(A): conflicts with S locks, so T3 waitsHeld: S by T1, T2; Queue: T3 (X)
4T1 and T2 commit and release their locksHeld: none
5T3 gets X(A), writes A, commitsHeld: X by T3
Final result: Readers ran together; the writer waited and then ran alone, so there is no conflict between T3 and the others.

3.2 Strict Two-Phase Locking (Strict 2PL)

Strict 2PL: the two rules Rule 1: A transaction must obtain an S lock on an object before reading it, and an X lock before writing it.
Rule 2: All locks held by a transaction are released only when the transaction completes (commits or aborts).

Note: Some books call the variant in which all locks (S and X) are held until the end rigorous 2PL, and use the name “strict 2PL” for the variant in which only X locks are held until the end. The notes here follow the first definition (all locks held to the end), which is common in DBMS textbooks; always check which definition your syllabus uses.

Why Strict 2PL works

  • Conflict serializable: Because locks are kept until the end, a transaction that conflicts with an earlier one has to wait until it has finished; this gives a serial-like order.
  • Strict (hence cascadeless and recoverable): No other transaction can read or overwrite an item written by T until T commits or aborts, so there are no dirty reads and no cascading aborts.
  • Simple: Easy to implement, and used in most commercial systems.
Common MistakeStrict 2PL does not prevent deadlocks. Two transactions can still wait for each other’s locks (Chapter 4).

3.3 Two-Phase Locking (2PL)

Basic 2PL RuleA transaction obtains all the locks it needs in a growing phase and then releases them in a shrinking phase. Once a transaction has released any lock, it cannot request any new lock.
Basic 2PL timelocks held lock point growingshrinking Strict 2PL time growingall locks held release atcommit/abort
Figure 3.1: Number of locks held over time under basic 2PL and under Strict 2PL.

The lock point is the moment at which the transaction holds its last lock (the end of the growing phase). The order of lock points of transactions gives an equivalent serial order, which is why 2PL guarantees conflict serializability.

Why every 2PL schedule is conflict serializable (idea)

Suppose Ti and Tj have conflicting actions on A, and Ti acts first. Ti must hold a lock on A that Tj cannot obtain until Ti releases it, and by the 2PL rule Ti has already acquired all its locks at that point (it releases only in the shrinking phase). So Ti’s lock point comes before Tj’s. Hence every edge Ti → Tj of the precedence graph goes from an earlier lock point to a later one, so the graph can have no cycle.

Variants of 2PL

VariantRuleEffect
Basic 2PLGrowing phase, then shrinking phase.Conflict serializable; may have cascading aborts (locks released before commit); deadlock possible.
Strict 2PLAll locks held until commit/abort.Conflict serializable and strict; deadlock possible.
Conservative (static) 2PLLock all required items before the transaction starts; wait if any is unavailable.Deadlock-free; but the items needed must be known in advance and concurrency is lower.

Example 2: Real-Life Application

Real-world situation: Two passengers try to book the last seat 14A on a train.
How the concept is applied: Booking transaction T1 takes an X lock on the seat record and marks it booked. T2’s X request is blocked. When T1 commits (Strict 2PL: lock released only at commit), T2 gets the lock, sees that the seat is already booked, and tells the passenger.
Learning outcome: Locking enforces isolation, which prevents double booking.

Example 3: Practical / Case Study (What goes wrong without 2PL)

Background: A = B = 1000. T1 transfers ₹100 from A to B. T2 adds 6% interest to A and B. Suppose each transaction locks and unlocks each item immediately after use (not 2PL).
Problem: Consider: X1(A) R1(A) W1(A) U1(A); X2(A) R2(A) W2(A) U2(A); X2(B) R2(B) W2(B) U2(B) C2; X1(B) R1(B) W1(B) U1(B) C1. Every request was legal in the lock table, yet T1 locks B after unlocking A.
Application of the concept:
  • Without 2PL: A = 900 × 1.06 = 954; B = 1000 × 1.06 = 1060, then T1 adds 100 to give 1160. Result (954, 1160); this equals neither serial result, (954, 1166) for T1;T2 or (960, 1160) for T2;T1.
  • With 2PL: T1 would keep X(A) until it has also obtained X(B). T2’s request X(A) would wait until T1 finishes, so the execution is equivalent to T1;T2 and gives (954, 1166).
Result: 2PL removes the non-serializable interleaving.
Conclusion: Merely taking locks is not enough; the two-phase rule is what guarantees serializability.

3.4 Introduction to Lock Management

The part of the DBMS that handles lock and unlock requests is the lock manager. Transactions send it requests; it grants, queues or refuses them.

T1 T2 T3 lock / unlock requests LOCKMANAGER Lock table (hash table on object id) Object A: mode X | holders: T1 | queue: T2(S), T3(X) Object B: mode S | holders: T2, T4 | queue: empty Object C: not locked Transaction table T1: holds {A}T2: holds {B}, waiting for {A}Used to release all locks at commit/abort Block diagram: how a lock manager keeps track of locks (illustrative).
Figure 3.2: Lock manager with lock table and transaction table.

Main parts and ideas

ItemExplanation
Lock tableA hash table keyed by object identifier. Each entry records the number of holders, the lock mode (S or X) and a pointer to the queue of waiting requests.
Transaction tableFor each transaction, a list of the locks it holds. It lets the lock manager release all locks quickly at commit or abort.
Request queueA request that cannot be granted waits in a queue, usually in first-come-first-served order to avoid starvation (a transaction waiting forever).
Atomic operationsLock and unlock requests must themselves be handled as indivisible actions, so that two transactions cannot both be granted a conflicting lock.
Lock upgrade / downgradeUpgrade: a transaction holding S asks for X on the same object (e.g. it read a row and now decides to update it); granted only if no other transaction holds a lock on it. Downgrade: X is converted to S, allowing other readers sooner. Two transactions both upgrading the same object can deadlock, so some systems use an update (U) lock when a transaction reads with the intention to write.
Lock granularityLocks can be placed on the whole database, a table, a page or a single record. Fine granularity (records) allows more concurrency but needs more lock overhead; coarse granularity (tables) is cheap but allows less concurrency. Systems that mix granularities use special intention locks on the higher levels.
Latches vs locksA latch is a very short-duration, low-cost lock used to protect the physical consistency of in-memory structures (for example, a page being read or written). A lock protects logical database objects for the whole transaction.
Key PointAt commit or abort, the lock manager uses the transaction table to release every lock of the transaction and then wakes up requests waiting in the queues of those objects.

3.5 Performance of Locking

Locking is safe, but it has a cost. Lock-based schemes resolve conflicts by two mechanisms: blocking (making a transaction wait) and aborting (and restarting) a transaction. Both lower performance.

  • Blocking: Waiting transactions hold their locks, which causes others to wait too, forming chains of blocked transactions. Time is wasted.
  • Aborts (restarts): When a deadlock is resolved, a victim transaction is rolled back and restarted. The work it has done is wasted. Aborts are fewer than blocks in most systems, so blocking is generally the main cost.

Throughput and thrashing

When the number of active transactions grows from small, throughput (transactions completed per unit time) first increases because more work overlaps. But more transactions also mean more conflicts. Beyond a point, adding more transactions makes more of them blocked, and throughput drops. This is called thrashing. Experience shows that thrashing begins when roughly 30% of the active transactions are blocked.

Number of active transactionsThroughput thrashing begins more transactions,more throughput too many blocked,throughput falls Conceptual curve: it shows the shape only, not measured data.
Figure 3.3: Throughput versus number of active transactions (thrashing).

How to improve locking performance

TechniqueHow it helps
Lock the smallest sensible objectA record lock blocks far fewer transactions than a table lock.
Reduce the time locks are heldKeep transactions short; do user interaction or slow computation outside the transaction; take X locks as late as possible.
Avoid hot spotsItems touched by many transactions (a global counter) cause queues; redesign to spread updates or delay them to the end of the transaction.
Use shared locks wherever possibleReaders do not block each other.
Limit the number of active transactionsAdmission control keeps the system below the thrashing point.
Run long reports in off-peak hoursLong transactions hold many locks for a long time.
Use lower isolation levels where acceptableFewer or shorter locks (see Chapter 5).

3.6 Applications, Advantages and Limitations

Applications

  • Banking: account updates by multiple tellers, ATMs and UPI at once.
  • Reservation systems: exclusive locks on seat or room records.
  • E-commerce: locking stock rows during order placement.
  • Enterprise systems (ERP, hospital, university portals): thousands of concurrent users updating shared records.
Advantages of locking (Strict 2PL)Limitations
Guarantees conflict serializability and recoverability.
Simple rules; widely supported.
Prevents lost updates and dirty reads.
Strict 2PL avoids cascading aborts.
Blocking reduces concurrency; thrashing at high load.
Deadlocks are possible and must be handled.
Lock management has overhead (memory and CPU).
Long transactions can block many others.

Important Points for Revision

Key Terminology Shared lock (S), exclusive lock (X), growing phase, shrinking phase, lock point, lock table, transaction table, latch, upgrade, starvation, thrashing, granularity.
Exam TipsAlways give the compatibility matrix and the two rules of Strict 2PL. When asked “why does 2PL ensure serializability”, mention the lock point. Draw Figure 3.1 (growing/shrinking graph) and the lock manager diagram.
Common MistakesWriting that 2PL prevents deadlock (it does not; only conservative 2PL does). Saying that basic 2PL avoids cascading aborts (only Strict 2PL does). Believing that taking locks alone ensures serializability. Confusing latches with locks.

Difference Between Important Concepts

Basis2PLStrict 2PL
Release of locksGradually in the shrinking phaseAll at commit/abort
SerializableYes (conflict)Yes (conflict)
Cascading abortsPossibleNone
DeadlockPossiblePossible
BasisShared lockExclusive lock
PurposeReadRead and write
Holders at a timeManyOne
Compatible with S?YesNo
BasisLockLatch
ProtectsLogical database objectsPhysical in-memory structures
DurationUntil transaction end (or earlier under 2PL)Very short
CostHigher (lock manager)Low
QUESTION BANK

Chapter 3: Questions with Answers

A. Multiple Choice Questions (20)

Q1. A shared (S) lock allows a transaction to:
A. Read an object, while other transactions may also read it
B. Write an object
C. Delete the database
D. Block all readers
Answer: A. S locks are compatible with other S locks.
Q2. An exclusive (X) lock on an object means:
A. Many readers can share it
B. Only the holder can access the object; no other lock on it is granted
C. It is read-only
D. It is released at once
Answer: B. X conflicts with both S and X.
Q3. Which pair of lock modes is compatible?
A. S and X
B. X and X
C. S and S
D. X and S (held X)
Answer: C. Only shared with shared is compatible.
Q4. In Strict 2PL, a transaction releases its locks:
A. After each read
B. Before writing
C. At random
D. Only at commit or abort
Answer: D. Holding locks to the end prevents dirty reads and overwrites.
Q5. The two phases of 2PL are:
A. Growing and shrinking
B. Reading and writing
C. Active and failed
D. Prepare and commit
Answer: A. Locks are acquired first and then released.
Q6. The lock point of a transaction is:
A. The time it starts
B. The moment it holds its last lock (end of growing phase)
C. The time of abort
D. The first unlock
Answer: B. Ordering transactions by lock point gives an equivalent serial order.
Q7. Under 2PL, after a transaction has released a lock, it:
A. May acquire any new lock
B. Must restart
C. Cannot acquire any new lock
D. Must commit at once
Answer: C. This is the defining rule of 2PL.
Q8. 2PL guarantees:
A. Deadlock freedom
B. No aborts
C. Cascadeless schedules always
D. Conflict serializability
Answer: D. Every 2PL schedule is conflict serializable.
Q9. Strict 2PL additionally ensures that schedules are:
A. Deadlock-free
B. Strict (no cascading aborts)
C. Serial
D. Non-recoverable
Answer: B. No one can read or overwrite uncommitted data.
Q10. Which problem is NOT prevented by Strict 2PL?
A. Deadlock
B. Lost update
C. Dirty read
D. Cascading abort
Answer: A. Transactions can still wait for each other in a cycle.
Q11. Conservative 2PL:
A. Locks items one at a time during execution
B. Never uses locks
C. Locks all needed items before starting, so it is deadlock-free
D. Releases locks at once
Answer: C. A transaction waits holding no locks until all are available.
Q12. A lock upgrade means converting:
A. X to S
B. A table lock into a page lock
C. A latch into a lock
D. S to X
Answer: D. The transaction needs write permission on an object it has read.
Q13. A lock table entry typically stores:
A. Lock mode, number of holders and a queue of waiting requests
B. Only the object name
C. SQL text
D. User passwords
Answer: A. This lets the lock manager decide quickly whether to grant a request.
Q14. A latch is:
A. A long-duration transaction lock
B. A short-duration lock protecting physical consistency of in-memory structures
C. A type of log record
D. An SQL command
Answer: B. Latches are cheaper and held very briefly.
Q15. Finer lock granularity (for example, record locks) generally gives:
A. Less concurrency and less overhead
B. Less concurrency and more overhead
C. More concurrency but more lock overhead
D. No change
Answer: C. More locks must be managed, but fewer transactions block.
Q16. Thrashing in locking systems occurs when:
A. Too many transactions are blocked and throughput falls
B. The log is full
C. The CPU is idle
D. There are no conflicts
Answer: A. Adding more transactions beyond the thrashing point reduces throughput.
Q17. Thrashing is observed in practice when roughly what fraction of active transactions are blocked?
A. 5%
B. 10%
C. 60%
D. 30%
Answer: D. About 30% is the commonly quoted empirical figure.
Q18. Which approach reduces lock contention?
A. Longer transactions
B. Smaller lock granularity and shorter transactions
C. Locking the whole database
D. Holding X locks early
Answer: B. Fewer objects locked for less time means fewer conflicts.
Q19. T1 holds an X lock on A. T2 requests an S lock on A. What happens?
A. T2 is granted at once
B. T1 aborts
C. T2 waits in the queue
D. Both abort
Answer: C. S and X are incompatible.
Q20. The two main performance costs of locking are:
A. Printing and sorting
B. Indexing and caching
C. Compilation and linking
D. Blocking and aborts (restarts)
Answer: D. Conflicts are resolved by making transactions wait or by aborting them.

B. Very Short Answer Questions (10)

1. What is a lock?
A lock is permission that a transaction must obtain on a data object before accessing it. It controls concurrent access so that conflicting operations do not interfere.
2. Name the two basic lock modes.
Shared (S) lock for reading and exclusive (X) lock for writing. Only S with S is compatible.
3. State the rules of Strict 2PL.
A transaction takes an S lock before reading and an X lock before writing an object. All its locks are released only when it commits or aborts.
4. What is the growing phase?
It is the phase of 2PL in which a transaction acquires locks and releases none. It ends at the lock point.
5. What is the shrinking phase?
It is the phase in which the transaction releases locks and may not acquire any new one.
6. What is a lock point?
The moment a transaction holds its last lock, that is, the end of the growing phase. It determines the serial order of 2PL transactions.
7. What is a lock manager?
It is the DBMS component that receives lock and unlock requests, keeps the lock table and transaction table, and grants, queues or refuses requests.
8. What is lock upgrade?
Converting a shared lock already held on an object into an exclusive lock, when the transaction decides to write what it has read.
9. What is thrashing?
The drop in throughput that occurs when too many transactions are active and most are blocked waiting for locks.
10. Does 2PL prevent deadlocks?
No. Transactions can still wait for each other in a cycle. Only conservative 2PL, which locks everything in advance, avoids deadlock.

C. Short Answer Questions (10)

1. Explain shared and exclusive locks with the compatibility matrix.
A shared lock lets a transaction read an object, and many transactions can hold S on the same object. An exclusive lock lets a transaction read and write, and only one transaction can hold it, with no S or X held by others. Compatibility: S–S granted; S–X, X–S, X–X must wait. This follows the conflict rule: two reads never conflict, but any pair containing a write does. Blocked requests are queued by the lock manager.
2. Explain Strict 2PL.
Strict 2PL has two rules. First, a transaction must hold an S lock to read and an X lock to write an object. Second, all locks are held until the transaction commits or aborts. Because conflicting transactions must wait until the holder finishes, schedules are conflict serializable. Since uncommitted data can neither be read nor overwritten, schedules are also strict, so there are no cascading aborts. It does not prevent deadlock.
3. Explain basic 2PL with its phases.
In basic 2PL, a transaction has a growing phase in which it only acquires locks and a shrinking phase in which it only releases locks. After the first release, no new lock may be requested. The moment of the last acquisition is the lock point. Ordering transactions by lock point gives an equivalent serial schedule, so every 2PL schedule is conflict serializable. However, it may allow cascading aborts and deadlocks.
4. How does Strict 2PL differ from basic 2PL?
Basic 2PL allows locks to be released gradually in the shrinking phase before the transaction ends. If an exclusive lock is released early, another transaction may read uncommitted data, so cascading aborts can happen. Strict 2PL holds all locks until commit or abort, so schedules are strict and recoverable. Both give conflict serializability, and both allow deadlocks.
5. What is conservative 2PL?
In conservative (static) 2PL a transaction requests all the locks it needs before it begins execution. If any lock is unavailable it waits, holding none. Since no transaction holds a lock while waiting for another, deadlock cannot occur. The disadvantage is that the transaction must know in advance everything it will access, and locks are held longer, so concurrency drops.
6. Describe the data structures of a lock manager.
The lock table is a hash table indexed by object id. Each entry stores the number of transactions holding a lock, the lock mode, and a pointer to a queue of waiting requests. The transaction table keeps, for every transaction, the list of locks it holds, so that all of them can be released at commit or abort. Lock and unlock operations are atomic.
7. Differentiate between a lock and a latch.
A lock protects a logical database object, such as a row or table, and is held for the life of the transaction (or until released under 2PL). It is managed by the lock manager and is relatively costly. A latch protects the physical integrity of in-memory structures, such as a buffer page while it is being read or modified, and is held only for a very short time with low overhead.
8. Why can lock upgrades cause deadlock and how can it be reduced?
Suppose T1 and T2 both hold S on A and both request an upgrade to X. Each waits for the other to release its S lock, so neither can proceed. This is a deadlock. To reduce it, systems may use an update (U) lock, taken when a transaction reads an object with the intention to write; only one transaction can hold it, so a second upgrader cannot arise.
9. Explain lock granularity.
Granularity is the size of the object locked: database, table, page or record. Fine granularity, such as record locks, lets more transactions work in parallel but needs many locks and more memory and CPU for management. Coarse granularity, such as table locks, is cheap to manage but blocks more transactions. Systems that support several levels use intention locks at the higher levels to detect conflicts efficiently.
10. Explain thrashing and one remedy.
As more transactions become active, throughput first increases, but conflicts also increase and more transactions become blocked. Beyond a point (roughly when 30% of active transactions are blocked), throughput falls instead of rising; this is thrashing. A remedy is to limit the number of active transactions through admission control, so that the system stays below the thrashing point. Shorter transactions and finer locks also help.

D. Long Answer Questions (5)

L1. Explain lock-based concurrency control and Strict Two-Phase Locking.
Introduction. A DBMS must prevent non-serializable and unrecoverable schedules while transactions run. Locking is the most common mechanism.
Lock modes. A shared lock (S) allows reading and can be held by many transactions. An exclusive lock (X) allows reading and writing and is held by only one transaction. Compatibility: only S–S is compatible; otherwise the requester waits in a queue.
Strict 2PL rules. (1) A transaction must hold S to read and X to write. (2) All locks are held until the transaction commits or aborts.
Why it works. If Ti and Tj conflict on an object, whichever transaction first obtains the lock keeps it until it finishes, so the other waits. The effect is the same as a serial execution in which the first transaction goes first, so the schedule is conflict serializable. Since nobody can read or overwrite an item written by an uncommitted transaction, schedules are strict: there are no dirty reads and no cascading aborts, and rollback is simple.
Example. Two passengers booking the last seat: the first takes X on the seat record; the second waits, then finds the seat booked after the first commits.
Limitations. It can cause deadlocks and reduces concurrency through blocking.
Conclusion. Strict 2PL is simple and safe, and is the basis of most commercial DBMSs.
L2. Explain the two-phase locking protocol. Prove that it ensures serializability and discuss its variants.
Protocol. In the growing phase a transaction acquires locks and releases none; in the shrinking phase it releases locks and acquires none. Once the first lock is released, the shrinking phase starts. The point where the last lock is acquired is the lock point (Figure 3.1).
Argument for serializability. Let Ti and Tj have conflicting actions on A with Ti first. Tj can lock A only after Ti releases its lock. Under 2PL, Ti releases only in its shrinking phase, so all of Ti’s locks, including its last one, were acquired before that release, and the lock point of Ti precedes the moment Tj gets the lock on A, which is before the lock point of Tj. Hence every edge Ti → Tj in the precedence graph goes from an earlier lock point to a later one. A cycle would require a lock point to precede itself, which is impossible. So the graph is acyclic and the schedule is conflict serializable; ordering transactions by lock point gives the equivalent serial schedule.
Variants. Strict 2PL holds all locks until commit/abort, giving strict schedules (no cascading aborts). Conservative 2PL acquires all locks before starting and is deadlock-free but needs advance knowledge.
Limitations. Basic 2PL permits cascading aborts and all variants except conservative can deadlock.
L3. Describe how a lock manager implements locking.
Role. The lock manager receives lock and unlock requests from transactions and decides to grant, queue or refuse them (Figure 3.2).
Lock table. A hash table on object identifiers. An entry records the number of transactions holding a lock, the lock mode and a pointer to the queue of waiting requests.
Transaction table. Each transaction has a list of the locks it holds, so that all can be released at commit or abort.
Processing a request. If the request is compatible with the locks currently held (and, for fairness, no earlier request is waiting), it is granted and the lock table is updated. Otherwise the transaction is queued and suspended. On release, the manager removes the lock and examines the queue to grant waiting requests, usually first-come-first-served, which prevents starvation.
Atomicity. Lock and unlock operations are executed atomically so that two transactions cannot both obtain conflicting locks.
Upgrades. A request to upgrade S to X is granted only when the requester is the sole holder; two simultaneous upgraders deadlock, which is why update locks may be used.
Latches. Short-duration latches protect the lock table and buffer pages physically, whereas locks protect logical objects.
Granularity. Locks may be at database, table, page or record level, trading concurrency against overhead.
Conclusion. An efficient lock manager is central to the correctness and speed of the DBMS.
L4. Discuss the performance of locking. What is thrashing and how can performance be improved?
Costs. Locking resolves conflicts by blocking and aborting. Blocking makes transactions wait while still holding their locks, creating chains of waiting transactions. Aborts occur when deadlocks are resolved; the victim’s work is wasted and it must restart. In most systems blocking is the larger cost.
Throughput curve. With few transactions, throughput rises as work overlaps. As the number of active transactions grows, so do conflicts. Beyond a point, more transactions only increase the blocked fraction, and throughput falls. This is thrashing, observed when about 30% of the active transactions are blocked (Figure 3.3).
Improvements.
  • Lock the smallest suitable objects (record rather than table).
  • Keep transactions short and hold locks for the minimum time; take X locks late.
  • Avoid hot spots (heavily updated items) by redesigning updates.
  • Prefer shared locks for reads and downgrade X to S when possible.
  • Limit the number of active transactions by admission control.
  • Run long reporting transactions in off-peak hours.
  • Use lower isolation levels when the application can tolerate them.
Conclusion. Good design of transactions and sensible limits on concurrency keep a locking system out of thrashing.
L5. Show with a numerical example that locking without the two-phase rule may not give serializability.
Setting. A = B = 1000. T1 transfers ₹100 from A to B. T2 adds 6% interest to both accounts.
Valid results. T1;T2 gives A = 900 × 1.06 = 954 and B = 1100 × 1.06 = 1166. T2;T1 gives A = 1060 − 100 = 960 and B = 1060 + 100 = 1160.
Non-2PL execution. Each transaction locks an item, uses it and unlocks it immediately. The order is: X1(A) R1(A) W1(A) U1(A); X2(A) R2(A) W2(A) U2(A); X2(B) R2(B) W2(B) U2(B) C2; X1(B) R1(B) W1(B) U1(B) C1. All lock requests are compatible, so the lock manager allows them. T1 writes A = 900; T2 reads 900 and writes 954; T2 reads B = 1000 and writes 1060; T1 reads 1060 and writes 1160. Result: (954, 1160). It equals neither valid result, so the schedule is not serializable. The precedence graph has T1 → T2 (on A) and T2 → T1 (on B).
With 2PL. T1 may not release X(A) before it acquires X(B). T2’s request for X(A) is blocked until T1 completes, giving the serial order T1;T2 and the result (954, 1166).
Conclusion. The two-phase rule, not merely the use of locks, guarantees serializability.

E. Application-Based Questions (5)

AQ1. A ticketing system uses table-level locks for seat booking, and users complain of delays during a popular sale. What do you suggest?
Model answer: Table locks make all bookings wait for each other. Use record (seat) level locks so only the transactions booking the same seat conflict. Also keep booking transactions short, and limit concurrency if the system begins thrashing.
AQ2. A long monthly report transaction holds S locks on account records for an hour, and tellers’ updates are blocked. How can this be improved?
Model answer: Schedule the report during off-peak hours, split it into smaller transactions, or run it at a lower isolation level if approximate figures are acceptable. This reduces blocking caused by long-held locks.
AQ3. Two transactions both read a row under S locks and then both try to update it. What happens and how can it be avoided?
Model answer: Each requests an upgrade to X, which needs the other to release its S lock, so they deadlock. This is avoided by taking an update (U) lock at the time of reading with intent to write, or by requesting X directly at the start.
AQ4. During a festival sale throughput of an e-commerce database drops as more customers log in, and about half of the transactions are blocked. Diagnose.
Model answer: The system is thrashing: too many active transactions cause blocking, and throughput falls. Apply admission control to limit active transactions, shorten transactions, avoid hot spots such as a single global counter and use finer lock granularity.
AQ5. T1 releases its X lock on A and then requests an S lock on B. Is T1 following 2PL? What anomaly may arise?
Model answer: No. After releasing a lock, a 2PL transaction cannot acquire another. Others may then see A updated while T1 is not finished (and may read uncommitted data), which can create non-serializable schedules and cascading aborts if T1 aborts.
PRACTICE TEST

Chapter 3 Assessment (Total 30 marks)

Section A: MCQs (10 × 1 = 10 marks)

1. Which lock mode is needed to write an object? (A) S (B) X (C) Latch (D) None
2. Compatible pair: (A) S–X (B) X–X (C) S–S (D) X–S
3. In 2PL, which is forbidden? (A) Locking in the growing phase (B) Acquiring a lock after releasing one (C) Releasing at the end (D) Reading under S
4. Strict 2PL avoids: (A) Cascading aborts (B) All deadlocks (C) All blocking (D) Logging
5. The lock manager stores waiting requests in: (A) A log (B) A queue (C) A page (D) An index
6. A deadlock-free 2PL variant is: (A) Basic (B) Strict (C) Conservative (D) Rigorous
7. Thrashing means: (A) Idle CPU (B) Falling throughput due to blocking (C) Disk failure (D) Log overflow
8. Record-level locking compared with table-level locking gives: (A) Less concurrency (B) More concurrency (C) No locks (D) No overhead
9. Short-duration lock for physical consistency is called: (A) Latch (B) X lock (C) Log (D) Index
10. The end of the growing phase is the: (A) Commit (B) Lock point (C) Abort (D) Checkpoint

Section B: Short answers (3 × 3 = 9 marks)

11. Write the compatibility matrix for S and X locks.
12. State the difference between 2PL and Strict 2PL.
13. What is a lock upgrade? Why can it cause trouble?

Section C: Descriptive (2 × 5.5 = 11 marks)

14. Explain how 2PL ensures conflict serializability. (5.5)
15. Explain the structure and working of a lock manager. (5.5)

Answer Key

MCQs: 1-B, 2-C, 3-B, 4-A, 5-B, 6-C, 7-B, 8-B, 9-A, 10-B.
Q11: S held / S requested: granted; S held / X requested: wait; X held / S requested: wait; X held / X requested: wait.
Q12: 2PL releases locks gradually in the shrinking phase and may cause cascading aborts; Strict 2PL holds all locks until commit/abort, so schedules are strict. Both are conflict serializable.
Q13: Converting S to X on an object already read. If two transactions holding S both request upgrade, each waits for the other: deadlock.
Q14: See L2 (lock point argument). Award 2 marks for the phases, 3.5 for the argument.
Q15: See L3 (lock table, transaction table, queue, atomicity, upgrade). Award 1 mark per component up to 5, 0.5 for diagram.
CHAPTER SUMMARY

Quick Revision: Chapter 3

Important Concepts
  • Locks: S for read, X for write; only S–S is compatible; incompatible requests wait in a queue.
  • Strict 2PL: S before read, X before write; all locks held until commit/abort → conflict serializable and strict.
  • 2PL: growing then shrinking phase; no lock after the first release; lock point gives the serial order.
  • Conservative 2PL: all locks upfront, deadlock-free but impractical for unknown access sets.
  • Lock manager: lock table (hash on object, holders, mode, queue), transaction table, atomic requests, upgrades, latches, granularity.
  • Performance: costs are blocking and aborts; thrashing at roughly 30% blocked; remedies include finer granularity, shorter transactions, fewer hot spots and limits on active transactions.
Five Most Important Examination Questions 1. Explain Strict 2PL and why it gives serializable, strict schedules.
2. Explain 2PL and its role in serializability.
3. Describe the working of a lock manager.
4. Explain thrashing and how to improve locking performance.
5. Compare lock modes, 2PL variants and locks versus latches.

Next: Chapter 4 – Dealing with Deadlocks

EDUKOSAL • www.edukosal.com • UG DBMS • Transaction Management • Chapter 3 • © EDUKOSAL. For learning use.
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
EDUKOSAL

Transaction Management

Database Management Systems • UG Study Notes

CHAPTER 4 OF 5 • READ-ONLY EDITION

www.edukosal.com

Book Plan

  1. Chapter 1 – Transactions, ACID Properties and Schedules
  2. Chapter 2 – Concurrent Execution, Serializability and Recoverability
  3. Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking
  4. Chapter 4 – Dealing with Deadlocks (this post)
  5. Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery

Inside Chapter 4: 4.1 What is a deadlock • 4.2 Conditions for deadlock • 4.3 Wait-for graph and deadlock detection • 4.4 Recovery: victim selection and rollback • 4.5 Timeouts • 4.6 Deadlock prevention (lock ordering, conservative 2PL, wait-die, wound-wait) • 4.7 Starvation and livelock • 4.8 Comparison, applications, advantages, limitations • Question bank • Practice test • Summary

EDUKOSAL • UG DBMSUnit: Transaction ManagementChapter 4
CHAPTER 4

Dealing with Deadlocks

Learning Outcomes After this chapter you will be able to: define a deadlock and state its four necessary conditions; draw a wait-for graph and detect deadlock from a cycle; choose a victim and explain rollback; explain timeouts; apply the wait-die and wound-wait schemes; and compare prevention, detection and timeout approaches.

4.1 What Is a Deadlock?

In Chapter 3 you saw that locking makes a transaction wait when another transaction holds a conflicting lock. Usually the holder finishes and the waiter proceeds. But sometimes transactions wait for each other in a circle, and none can ever proceed.

Everyday analogy: Two vehicles meet on a narrow bridge from opposite ends. Each is waiting for the other to back up. Neither moves. They are in a deadlock.

Definition: DeadlockA deadlock is a situation in which a set of transactions is waiting for locks in such a way that each transaction in the set is waiting for a lock held by another transaction in the set. None of them can proceed unless the DBMS intervenes.
T1 T2 Item A Item B X-lock held by T1 X-lock held by T2 T1 waits for B T2 waits for A DEADLOCKsolid = holds, dashed = waits
Figure 4.1: T1 holds A and waits for B; T2 holds B and waits for A.

Example 1: Basic Example

Problem / Situation: T1 needs X locks on A and then B. T2 needs X locks on B and then A.
Explanation: Each transaction gets its first lock, then requests the second one that the other holds.
Step-by-step solution:
StepT1T2Outcome
1X(A) grantedT1 holds A
2X(B) grantedT2 holds B
3X(B) requestedT1 waits for T2
4X(A) requestedT2 waits for T1
Final result: T1 waits for T2 and T2 waits for T1. Neither can commit and release locks, so both wait forever unless the DBMS aborts one of them.

4.2 Conditions for Deadlock

A deadlock can occur only when all four of the following conditions hold at the same time. If a method of locking breaks any one condition, deadlock cannot happen.

ConditionMeaningIn locking
1. Mutual exclusionA resource can be held by only one transaction at a time.X locks are exclusive.
2. Hold and waitA transaction holds some locks while waiting for others.T1 holds A and waits for B.
3. No preemptionA lock cannot be forcibly taken away; the holder must release it.Locks are released only at commit/abort (Strict 2PL).
4. Circular waitA cycle of transactions exists, each waiting for a lock held by the next.T1 → T2 → T1.
Key PointPrevention methods work by breaking one of these conditions. For example, conservative 2PL breaks hold and wait, lock ordering breaks circular wait, and wound-wait breaks no preemption.

4.3 Wait-For Graph and Deadlock Detection

The DBMS can allow deadlocks to happen and then detect and resolve them. The tool for detection is the wait-for graph, which the lock manager can build from its lock table and request queues.

Wait-for graphA directed graph whose nodes are the active transactions. There is an edge Ti → Tj if Ti is waiting for Tj to release a lock. A deadlock exists if and only if the graph contains a cycle.

Working process

  1. Whenever a lock request cannot be granted, note which transactions hold the conflicting lock; add edges from the requester to those holders.
  2. When a lock is released or a transaction ends, remove the related edges.
  3. Check the graph for a cycle periodically (for example, every few seconds), or when a transaction has waited for a long time.
  4. If a cycle is found, choose a victim in the cycle, abort it, and let others continue.
Before: cycle found T1 T2 T3 T1 → T2 → T3 → T1: DEADLOCK After: T3 aborted (victim) T1 T2 T3 No cycle: T2 can proceed, then T1
Figure 4.2: Wait-for graph with a cycle, and the graph after the victim T3 is aborted.

Example 2: Real-Life Application

Real-world situation: A bank has accounts 101 and 202. At the same moment, transaction T1 transfers ₹500 from 101 to 202, and T2 transfers ₹300 from 202 to 101. Each transaction first locks the account it debits and then the account it credits.
How the concept is applied: T1 locks 101 and T2 locks 202. T1 now needs 202 and T2 needs 101. The wait-for graph has T1 → T2 and T2 → T1: a cycle. The DBMS aborts one transaction (the victim); the other completes; the victim is restarted and then completes as well.
Learning outcome: Transfers in opposite directions are a classic source of deadlock. A good design avoids it by always locking accounts in a fixed order (for example, lower account number first); then both transactions would try 101 first, and one would simply wait.

Example 3: Practical / Case Study

Background: Three transactions run: T1 holds X(A), T2 holds X(B), T3 holds X(C).
Problem: T1 requests X(B) and waits. T2 requests X(C) and waits. T3 requests X(A) and waits. Is there a deadlock? Which transaction should be aborted?
Application of the concept: Edges: T1 → T2 (T1 waits for B held by T2), T2 → T3, T3 → T1. This is a cycle, so deadlock. Suppose T3 has done the least work (fewest locks and updates); choose T3 as the victim and roll it back. Its lock on C is released, so T2 gets C; and T3’s request for A is cancelled.
Result: T2 completes and releases B, then T1 gets B and completes. T3 is restarted later.
Conclusion: Aborting one transaction in the cycle is enough to break the deadlock, so the cost is the work lost by the victim.

4.4 Recovery from Deadlock: Victim Selection and Rollback

Choosing the victim

The DBMS should abort the transaction whose abort costs least. Common criteria are:

CriterionReason
Fewest locks heldLess to release and usually less work done.
Least work done so farLess wasted effort when rolled back.
Youngest transaction (latest start)Older transactions have invested more.
Fewest transactions to be rolled back with itAvoids cascading effects.
Not chosen repeatedlyPrevents starvation of one transaction.

Rollback

  • Total rollback: abort the victim completely and restart it. Simple and most common.
  • Partial rollback: roll back only as far as is needed to release the lock that breaks the cycle. Less wasted work, but the system must track more information.

After rollback, the victim’s locks are released, waiting transactions are given the locks, and the victim is usually restarted automatically, or an error is returned to the application so that it can retry.

4.5 Timeouts

A very simple method is to give each lock wait a time limit. If a transaction has waited longer than the limit, the DBMS assumes it is deadlocked and aborts it.

AdvantagesLimitations
Very easy to implement; no graph is needed.
Works well when deadlocks are rare.
Difficult to choose a good limit: too short aborts transactions that were only slow; too long leaves real deadlocks unresolved.
May abort innocent waiting transactions.

4.6 Deadlock Prevention

Instead of detecting deadlocks, the DBMS can use rules that make them impossible.

(a) Conservative 2PL

A transaction acquires all its locks before it starts. If any lock is unavailable it waits holding nothing. It breaks the hold-and-wait condition. Drawback: the transaction needs to know in advance what it will access, and locks are held longer.

(b) Lock ordering

All data items are given a fixed order (for example, by account number), and every transaction must request locks in that order. A cycle is impossible because waits always go from lower to higher items. It breaks circular wait. Drawback: needs knowledge of what will be accessed.

(c) Priority-based schemes using timestamps

Each transaction gets a timestamp when it starts. An older transaction (smaller timestamp) has higher priority. Suppose Ti requests a lock held by Tj.

SchemeIf Ti has higher priority (older)If Ti has lower priority (younger)Type
Wait-DieTi waits for TjTi dies (is aborted and restarted)Non-preemptive
Wound-WaitTi wounds Tj (Tj is aborted and restarted); Ti gets the lockTi waits for TjPreemptive
  • In both schemes, an aborted transaction is restarted with its original timestamp. Over time it becomes the oldest and gets the highest priority, so it cannot be starved.
  • In both schemes, waits go in only one direction of age (Wait-Die: older waits for younger; Wound-Wait: younger waits for older), so a cycle cannot form.
  • These schemes may abort transactions even when no deadlock would have happened.
Wait-Die Ti requests lock held by Tj Is Ti older than Tj? yes no Ti WAITS Ti DIES (abort) Wound-Wait Ti requests lock held by Tj Is Ti older than Tj? yes no Tj WOUNDED(aborted); Ti proceeds Ti WAITS
Figure 4.3: Decision flow of Wait-Die and Wound-Wait.

Worked Example: Wait-Die and Wound-Wait

Situation: Timestamps: T1 = 10 (oldest), T2 = 20, T3 = 30 (youngest). A smaller timestamp means higher priority.
CaseRequestWait-Die resultWound-Wait result
1T1 requests a lock held by T2 (older requests from younger)T1 is older, so T1 waitsT1 is older, so T2 is wounded; T1 gets the lock
2T3 requests a lock held by T1 (younger requests from older)T3 is younger, so T3 diesT3 is younger, so T3 waits
3T2 requests a lock held by T3T2 is older, so T2 waitsT2 is older, so T3 is wounded
Learning outcome: Wait-Die makes the requester die; Wound-Wait makes the holder get aborted. In both cases, no cycle can arise.

4.7 Starvation and Livelock

TermMeaningExample / remedy
DeadlockTransactions wait for each other in a cycle; nobody progresses.Detect and abort a victim, or prevent.
StarvationA transaction waits indefinitely (or is aborted again and again) while others proceed.A transaction always chosen as victim, or a writer kept waiting behind a stream of readers. Remedy: first-come-first-served lock queues; do not pick the same victim repeatedly; restart with the original timestamp.
LivelockTransactions keep changing state (running, aborting, restarting) but make no useful progress.Two transactions repeatedly abort each other. Remedy: use priorities and random back-off before restart.

4.8 Comparison, Applications, Advantages and Limitations

BasisDetection and recoveryTimeoutPrevention (wait-die / wound-wait, ordering, conservative 2PL)
IdeaAllow deadlock; find cycle in wait-for graph; abort a victim.Abort transactions that wait too long.Rules make cycles impossible.
OverheadGraph maintenance and periodic checks.Very low.Extra aborts, or advance knowledge of locks.
Unnecessary abortsNone (only real deadlocks).Possible (false alarms).Possible (aborts even when no deadlock).
Best whenDeadlocks are infrequent.Simplicity is wanted.Deadlocks are frequent or must be avoided.

Since deadlocks are relatively rare in most workloads, many practical DBMSs prefer detection (wait-for graph) or timeouts over prevention.

Applications

  • Banking: opposite-direction transfers between accounts.
  • Order processing and inventory: orders that update the same stock rows in a different order.
  • Reservation systems: multi-seat or multi-leg bookings that lock several records.
  • Application design: programmers reduce deadlocks by accessing tables and rows in a consistent order and by keeping transactions short.
Advantages of deadlock handlingLimitations
System keeps running instead of freezing.
Detection aborts only when a real deadlock exists.
Prevention schemes give guaranteed absence of deadlock.
Timestamps give fairness (no starvation).
Aborted transactions waste work and must be restarted.
Detection has overhead.
Prevention may abort unnecessarily.
Timeouts need careful tuning.

Important Points for Revision

Key Terminology Deadlock, wait-for graph, cycle, victim, total / partial rollback, timeout, wait-die, wound-wait, timestamp, starvation, livelock.
Exam TipsDraw the wait-for graph whenever you are asked to detect a deadlock, and name the cycle. For wait-die and wound-wait, always say who is older, who waits and who aborts. State that the aborted transaction is restarted with its original timestamp.
Common MistakesMixing up the two schemes (in wait-die the younger requester aborts; in wound-wait the younger holder is aborted). Saying that every wait means deadlock (only a cycle does). Forgetting that Strict 2PL does not prevent deadlock. Confusing starvation with deadlock.

Difference Between Important Concepts

BasisWait-DieWound-Wait
Older requests from youngerOlder waitsYounger holder is aborted
Younger requests from olderYounger diesYounger waits
TypeNon-preemptivePreemptive
BasisDeadlock preventionDeadlock detection
When it actsBefore waits can form cyclesAfter a deadlock has formed
CostPossible unnecessary abortsGraph checks; abort of victim
Typical useFrequent conflictsMost commercial DBMSs
BasisDeadlockStarvation
CauseCircular waitUnfair scheduling or repeated victim choice
AffectedA group of transactionsUsually a single transaction
RemedyAbort a victim / prevent cyclesFCFS queues, original timestamp
QUESTION BANK

Chapter 4: Questions with Answers

A. Multiple Choice Questions (20)

Q1. A deadlock is a situation in which:
A. A set of transactions each wait for a lock held by another in the set
B. A transaction commits
C. The disk fails
D. A query is slow
Answer: A. The circular waiting means that none of the transactions can proceed.
Q2. Which is NOT a necessary condition for deadlock?
A. Mutual exclusion
B. Hold and wait
C. Circular wait
D. Preemption of locks
Answer: D. The condition is no preemption; if locks could be taken away, deadlock could be broken.
Q3. The nodes of a wait-for graph are:
A. Data items
B. Transactions
C. Locks
D. Pages
Answer: B. Each active transaction is a node.
Q4. An edge Ti → Tj in a wait-for graph means:
A. Ti committed before Tj
B. Tj is waiting for Ti
C. Ti is waiting for a lock held by Tj
D. Ti and Tj are identical
Answer: C. The edge points from the waiter to the holder.
Q5. A deadlock exists if and only if the wait-for graph contains:
A. A cycle
B. A tree
C. An isolated node
D. No edges
Answer: A. A cycle is the signature of circular wait.
Q6. In the timeout approach, a transaction is aborted when:
A. It commits
B. It has waited for a lock longer than the time limit
C. It reads data
D. It starts
Answer: B. The DBMS assumes that a long wait indicates deadlock.
Q7. The transaction chosen to be aborted to break a deadlock is called the:
A. Leader
B. Master
C. Victim
D. Parent
Answer: C. It is chosen so as to minimise the cost of rollback.
Q8. Starvation occurs when:
A. The CPU is idle
B. A query returns no rows
C. The log is full
D. A transaction waits or is aborted repeatedly and never progresses
Answer: D. For example, the same transaction is always selected as the victim.
Q9. In Wait-Die, when Ti requests a lock held by Tj and Ti is older:
A. Ti waits
B. Ti dies
C. Tj is aborted
D. Both abort
Answer: A. In Wait-Die, an older requester waits for a younger holder.
Q10. In Wound-Wait, when Ti requests a lock held by Tj and Ti is older:
A. Ti waits
B. Ti dies
C. Tj is aborted (wounded) and Ti gets the lock
D. Both wait
Answer: C. The older transaction preempts the younger one.
Q11. Wait-Die is:
A. Preemptive
B. Non-preemptive
C. A detection scheme
D. A logging scheme
Answer: B. A lock holder is never aborted by a requester; only the requester may abort.
Q12. Wound-Wait is:
A. Non-preemptive
B. A timeout scheme
C. A detection scheme
D. Preemptive
Answer: D. An older requester can force a younger holder to abort.
Q13. In both Wait-Die and Wound-Wait an aborted transaction restarts with its:
A. New (later) timestamp
B. No timestamp
C. Original timestamp
D. Random timestamp
Answer: C. It eventually becomes the oldest and is no longer starved.
Q14. Which method prevents deadlock by acquiring all locks before the transaction starts?
A. Conservative 2PL
B. Strict 2PL
C. Timeouts
D. Wait-for graph
Answer: A. It removes the hold-and-wait condition.
Q15. Requesting locks in a fixed global order prevents deadlock by breaking:
A. Mutual exclusion
B. Circular wait
C. Durability
D. Atomicity
Answer: B. Waits always point toward later items, so cycles are impossible.
Q16. A DBMS that uses detection usually checks the wait-for graph:
A. Never
B. Only at shutdown
C. Only when a transaction commits
D. Periodically or when a transaction has waited a long time
Answer: D. Checking at intervals balances overhead and delay.
Q17. When transactions keep aborting and restarting without useful progress, it is called:
A. Livelock
B. Commit
C. Checkpoint
D. Latching
Answer: A. They are active but make no progress.
Q18. To resolve a cycle T1 → T2 → T1 in the wait-for graph, the DBMS should:
A. Commit both
B. Do nothing
C. Abort one transaction in the cycle
D. Delete the data
Answer: C. Aborting one releases its locks and breaks the cycle.
Q19. Which statement is true about practical DBMSs?
A. They never have deadlocks
B. Many rely on detection or timeouts, since deadlocks are relatively rare
C. They use no locking
D. They always use conservative 2PL
Answer: B. Detection and timeouts have low cost when deadlocks are infrequent.
Q20. T1 and T2 both hold S locks on A and both request an upgrade to X. The result is:
A. Both succeed
B. T1 aborts at once always
C. No effect
D. A deadlock
Answer: D. Each waits for the other to release its S lock.

B. Very Short Answer Questions (10)

1. Define deadlock.
A deadlock is a situation in which a set of transactions each wait for a lock held by another transaction of the set, so none can proceed.
2. List the four conditions for deadlock.
Mutual exclusion, hold and wait, no preemption and circular wait. All four must hold together for a deadlock to occur.
3. What is a wait-for graph?
A directed graph with transactions as nodes and an edge Ti → Tj when Ti waits for a lock held by Tj. A cycle in it means deadlock.
4. What is a victim?
The transaction chosen for abort to break a deadlock. It is usually the one whose rollback is cheapest.
5. What is a timeout in deadlock handling?
A limit on how long a transaction may wait for a lock. After it is exceeded the transaction is assumed deadlocked and is aborted.
6. State the Wait-Die rule.
If the requester is older than the holder it waits; if it is younger it dies (aborts and restarts).
7. State the Wound-Wait rule.
If the requester is older it wounds (aborts) the holder and takes the lock; if it is younger it waits.
8. What is starvation?
A transaction is made to wait or is aborted repeatedly and never completes, while other transactions proceed normally.
9. What is livelock?
Transactions keep running or restarting but make no useful progress, for example by repeatedly aborting each other.
10. How does conservative 2PL prevent deadlock?
It acquires all required locks before the transaction begins. A transaction never holds locks while waiting, so hold-and-wait and thus deadlock cannot occur.

C. Short Answer Questions (10)

1. Explain deadlock with an example.
A deadlock is a state in which each transaction in a group waits for a lock held by another in the group. For example, T1 holds an X lock on A and requests B, while T2 holds an X lock on B and requests A. T1 waits for T2 and T2 waits for T1. Neither can commit or release its lock, so both wait forever unless the DBMS aborts one of them.
2. Explain the four necessary conditions of deadlock.
Mutual exclusion: a lock such as X can be held by only one transaction. Hold and wait: a transaction holds locks while requesting more. No preemption: locks cannot be forcibly taken, they are released only voluntarily at the end. Circular wait: there is a cycle of transactions each waiting for the next. If any one of these is removed by the locking scheme, deadlock cannot happen.
3. How is deadlock detected using a wait-for graph?
The lock manager records, for each blocked request, an edge from the waiting transaction to each transaction holding the conflicting lock. Edges are removed when locks are released. Periodically the DBMS searches the graph for a cycle. If there is a cycle there is a deadlock, and one transaction of the cycle is chosen as victim and aborted. If there is no cycle, waiting transactions will eventually proceed.
4. What factors decide the choice of victim?
The aim is to minimise the cost of abort. Preferred victims hold the fewest locks, have done the least work, or are the youngest. The system also considers how many other transactions would have to be rolled back, and avoids selecting the same transaction again and again, because that would cause starvation. The victim is rolled back and normally restarted.
5. Differentiate total and partial rollback.
In total rollback, the victim is aborted completely and restarted from the beginning, which is simple. In partial rollback, the victim is rolled back only to the point where the lock that breaks the cycle is released, then it resumes. Partial rollback wastes less work but needs the system to keep extra information about the state at each lock request.
6. Discuss the timeout method of handling deadlocks.
Each lock wait has a time limit. A transaction that waits longer is aborted and may be restarted. The method is simple and has little overhead, so it suits systems where deadlocks are rare. Its drawback is the difficulty of choosing the limit: if too short, slow but healthy transactions are aborted; if too long, true deadlocks remain unresolved and waste time.
7. Explain Wait-Die with an example.
Each transaction has a timestamp and older ones have higher priority. When Ti requests a lock held by Tj: if Ti is older it waits; if Ti is younger it aborts (dies) and restarts with its original timestamp. Example: T1 (ts 10) requests a lock held by T2 (ts 20): T1 waits. T3 (ts 30) requests a lock held by T1: T3 dies. Waiting is allowed only from older to younger, so no cycle can form.
8. Explain Wound-Wait with an example.
When Ti requests a lock held by Tj: if Ti is older, it wounds Tj, which is aborted and restarted, and Ti takes the lock; if Ti is younger, it waits. Example: T1 (ts 10) requests a lock held by T2 (ts 20): T2 is aborted. T3 (ts 30) requests a lock held by T1: T3 waits. Waiting goes only from younger to older, so cycles cannot form. The scheme is preemptive.
9. Why is the original timestamp retained on restart?
If a restarted transaction got a new timestamp it would be young again and could be aborted repeatedly, causing starvation. With its original timestamp, it grows relatively older as other transactions arrive, and eventually has the highest priority. Then it is never aborted by the scheme, and so it is guaranteed to complete.
10. How can application programmers reduce deadlocks?
They can access tables and rows in a consistent order in all transactions, keep transactions short, avoid user interaction while locks are held, request exclusive locks directly when updating (rather than reading then upgrading), and use lower granularity of locks. They should also write code to retry a transaction that is aborted as a deadlock victim.

D. Long Answer Questions (5)

L1. What is a deadlock? Explain its conditions and how a wait-for graph is used to detect it.
Definition. A deadlock is a state in which each transaction of a set waits for a lock held by another transaction of the set, so none can proceed (Figure 4.1).
Conditions. Four conditions must hold: mutual exclusion (X locks are exclusive); hold and wait (a transaction holds locks and waits for more); no preemption (locks released only voluntarily, at commit/abort under Strict 2PL); circular wait (a cycle of waiting transactions).
Example. T1 holds A and requests B; T2 holds B and requests A.
Wait-for graph. Nodes are active transactions. An edge Ti → Tj means Ti waits for a lock held by Tj. The lock manager adds edges when a request is blocked and removes them on release. A deadlock exists if and only if the graph has a cycle. In the example, T1 → T2 and T2 → T1 form a cycle.
Detection procedure. The graph is examined periodically (or when a transaction has waited long). If a cycle is found, a victim is chosen and aborted; its locks are released and the other transactions proceed (Figure 4.2).
Conclusion. Wait-for graph detection finds only real deadlocks, so it avoids unnecessary aborts.
L2. Explain deadlock prevention techniques, including Wait-Die and Wound-Wait.
Idea. Prevention uses rules that make at least one deadlock condition impossible.
Conservative 2PL. All locks are acquired before the transaction begins; if any is unavailable, it waits holding nothing. It breaks hold-and-wait but requires advance knowledge and reduces concurrency.
Lock ordering. Items have a fixed order and locks are requested in that order. Waits then always go to later items and circular wait is impossible.
Timestamp-based priority schemes. Each transaction gets a timestamp at start; older means higher priority. If Ti requests a lock held by Tj:
Wait-Die: if Ti is older it waits; otherwise Ti dies (aborts and restarts). It is non-preemptive.
Wound-Wait: if Ti is older it wounds Tj, which is aborted, and Ti gets the lock; otherwise Ti waits. It is preemptive.
Since waiting goes in only one direction of age, no cycle can form. An aborted transaction restarts with its original timestamp, so it eventually becomes the oldest and is not starved.
Example. T1 (ts 10), T2 (20), T3 (30). T1 requests a lock held by T2: Wait-Die: T1 waits; Wound-Wait: T2 is aborted. T3 requests a lock held by T1: Wait-Die: T3 dies; Wound-Wait: T3 waits.
Drawback. Transactions may be aborted even when no deadlock would have occurred.
L3. Describe recovery from a deadlock. How is a victim selected and how are rollbacks performed?
Steps after detection. (1) Select a victim from the transactions in the cycle. (2) Roll it back. (3) Release its locks and grant them to waiting transactions. (4) Restart the victim or inform the application.
Victim selection. The aim is to minimise cost. Criteria: fewest locks held, least work done, youngest, fewest other transactions that would have to be rolled back, and not the same transaction repeatedly (to avoid starvation).
Rollback. Total rollback aborts the victim completely and restarts it. It is simple and widely used. Partial rollback undoes only as much as needed to release the lock that breaks the cycle and then resumes; it wastes less work but needs more bookkeeping.
Starvation. If the same transaction is always the cheapest victim it may never finish. Including the number of previous rollbacks (or the original timestamp) in the cost solves this.
Example. In a cycle T1 → T2 → T3 → T1, T3 has done the least work and is aborted. T2 obtains the lock held by T3, completes, and then T1 completes. T3 is restarted.
Conclusion. Careful victim selection limits wasted work and keeps the system fair.
L4. Compare the deadlock handling approaches: detection, timeout and prevention.
Detection and recovery. Transactions are allowed to deadlock. A wait-for graph is built and checked periodically for cycles; a victim is aborted. Only real deadlocks cause aborts. Overhead: maintaining and checking the graph. Suitable when deadlocks are infrequent.
Timeout. Aborts any transaction that waits longer than a limit. Very simple and cheap, but may abort transactions that were only slow, and a poorly chosen limit leaves real deadlocks unresolved or causes false aborts.
Prevention. Conservative 2PL, lock ordering, Wait-Die and Wound-Wait ensure that cycles cannot form. No detection is needed. But they may abort transactions needlessly, or need advance knowledge of the locks required.
BasisDetectionTimeoutPrevention
Unnecessary abortsNonePossiblePossible
OverheadGraph checksMinimalRestarts or advance planning
GuaranteeResolves deadlock after it formsResolves eventuallyNo deadlock
Practice. Since deadlocks are rare in many workloads, many DBMSs use detection or timeouts. Prevention is considered where conflicts are frequent. Application design (consistent lock order, short transactions) also reduces deadlocks.
L5. Three transactions T1, T2, T3 hold X(A), X(B), X(C) respectively. T1 requests B, T2 requests C and T3 requests A. Analyse using a wait-for graph and show how each approach resolves it.
Wait-for graph. T1 waits for T2 (B), T2 waits for T3 (C), T3 waits for T1 (A). The edges T1 → T2 → T3 → T1 form a cycle, so a deadlock exists.
Detection and recovery. The detector finds the cycle and picks a victim, say T3 (least work). T3 is rolled back, releasing C. T2 gets C, completes and releases B. T1 gets B and completes. T3 restarts later.
Timeout. After the time limit expires, the transaction that has waited longest (or any waiting one) is aborted; the others continue as above. A slow but not deadlocked transaction might also be aborted by mistake.
Wait-Die (timestamps T1 = 10, T2 = 20, T3 = 30). T1 requests B held by T2: T1 is older, so it waits. T2 requests C held by T3: T2 is older, so it waits. T3 requests A held by T1: T3 is younger, so it dies; its lock on C is released and the cycle never forms.
Wound-Wait. T1 requests B held by T2: T1 is older, so T2 is wounded and aborted; T1 gets B. T3 requesting A (held by T1) waits as it is younger. No cycle forms.
Lock ordering. If all transactions lock in the order A, B, C then T3 would request A before C, and no cycle can occur.
Conclusion. Every approach breaks the cycle by aborting or avoiding a wait, but at different cost.

E. Application-Based Questions (5)

AQ1. Two UPI-style transfers between accounts 101 and 202 run in opposite directions and both hang. Diagnose and suggest a design fix.
Model answer: Each holds the debit account lock and waits for the credit account: a deadlock (T1 → T2 → T1). Fix: always lock accounts in a fixed order such as ascending account number, so both transactions attempt 101 first and one simply waits. Also have the application retry a transaction aborted as a victim.
AQ2. A system frequently aborts a long-running report because it is always the youngest in a cycle. Which problem is this and what is the remedy?
Model answer: Starvation due to repeated victim selection. Include the number of earlier aborts (or the original timestamp) in the victim selection so that the report eventually gets high priority and is not chosen again.
AQ3. Timestamps: T1 = 5, T2 = 15. T2 holds a lock that T1 requests. What happens under Wait-Die and Wound-Wait?
Model answer: T1 is older. Wait-Die: T1 waits. Wound-Wait: T2 is wounded (aborted and restarted with timestamp 15) and T1 gets the lock.
AQ4. A database team sets a lock timeout of 1 second and sees many aborted transactions that were not deadlocked. What is wrong and what can they do?
Model answer: The timeout is too short, so slow but healthy transactions are aborted. They should increase the limit, or use wait-for graph detection to abort only real deadlocks, and also shorten transactions to reduce waiting.
AQ5. The wait-for graph has edges T1 → T2, T2 → T3, T4 → T3. Is there a deadlock?
Model answer: No. The graph has no cycle (T3 waits for nobody). T3 will finish, then T2 and T4 can proceed, and then T1. The transactions are only waiting, not deadlocked.
PRACTICE TEST

Chapter 4 Assessment (Total 30 marks)

Section A: MCQs (10 × 1 = 10 marks)

1. A deadlock requires: (A) Circular wait (B) No locks (C) Only S locks (D) Only one transaction
2. A cycle in the wait-for graph means: (A) Commit (B) Deadlock (C) Checkpoint (D) Latch
3. Wait-Die: a younger requester: (A) Waits (B) Dies (C) Wounds the holder (D) Commits
4. Wound-Wait: an older requester: (A) Waits (B) Dies (C) Wounds the holder (D) Is ignored
5. The chosen transaction to abort is the: (A) Victim (B) Leader (C) Parent (D) Coordinator
6. Fixed lock ordering prevents: (A) Circular wait (B) Mutual exclusion (C) Logging (D) Commit
7. Livelock means: (A) No transactions (B) Transactions active but no progress (C) Disk failure (D) Log overflow
8. A disadvantage of timeouts: (A) Needs a graph (B) May abort non-deadlocked transactions (C) Impossible to implement (D) Always prevents deadlock
9. Restarted transactions keep their: (A) New timestamp (B) Original timestamp (C) No timestamp (D) Random timestamp
10. Which prevention method locks everything in advance? (A) Conservative 2PL (B) Strict 2PL (C) Wait-Die (D) Timeout

Section B: Short answers (3 × 3 = 9 marks)

11. Name the four conditions of deadlock.
12. Differentiate Wait-Die and Wound-Wait.
13. Why can a long wait not always be treated as a deadlock?

Section C: Descriptive (2 × 5.5 = 11 marks)

14. Explain deadlock detection with a wait-for graph and victim selection. (5.5)
15. T1 (ts 10), T2 (ts 20), T3 (ts 30). T1 holds X(A), T2 holds X(B). T2 requests A, then T3 requests B, then T1 requests B. Show what happens under Wait-Die. (5.5)

Answer Key

MCQs: 1-A, 2-B, 3-B, 4-C, 5-A, 6-A, 7-B, 8-B, 9-B, 10-A.
Q11: Mutual exclusion, hold and wait, no preemption, circular wait.
Q12: Wait-Die: older requester waits, younger requester dies (non-preemptive). Wound-Wait: older requester aborts the holder, younger requester waits (preemptive).
Q13: A transaction may be waiting for a slow but active transaction that will finish; only a cycle proves deadlock. Timeouts may therefore abort healthy transactions.
Q14: See L1 and L3. Award 2 marks for graph and cycle, 2 for victim criteria, 1.5 for rollback and restart.
Q15: T2 (ts 20) requests A held by T1 (ts 10): T2 is younger, so T2 dies and releases B. T3 requests B: B is now free (T2 released it when it died), so it is granted. T1 requests B held by T3 (ts 30): T1 is older, so it waits. When T3 commits, T1 gets B. T2 restarts with timestamp 20. No deadlock arises. Award marks for each step with the age comparison.
CHAPTER SUMMARY

Quick Revision: Chapter 4

Important Concepts
  • Deadlock: each transaction in a set waits for a lock held by another in the set. Needs mutual exclusion, hold and wait, no preemption and circular wait.
  • Wait-for graph: nodes are transactions; Ti → Tj means Ti waits for Tj. Deadlock if and only if there is a cycle.
  • Recovery: choose a cheap victim (few locks, little work, youngest), roll back (total or partial), restart; avoid choosing the same victim repeatedly.
  • Timeouts: simple but may abort healthy transactions.
  • Prevention: conservative 2PL, lock ordering, Wait-Die (younger requester dies), Wound-Wait (older requester wounds holder); restart with original timestamp.
  • Starvation: indefinite waiting or repeated abort. Livelock: active but no progress.
  • Many commercial DBMSs use detection or timeouts, since deadlocks are relatively rare.
Five Most Important Examination Questions 1. Define deadlock; explain conditions and the wait-for graph.
2. Explain deadlock prevention: Wait-Die and Wound-Wait.
3. How is a victim selected and how is rollback done?
4. Compare detection, timeout and prevention.
5. Distinguish deadlock, starvation and livelock.

Next: Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery

EDUKOSAL • www.edukosal.com • UG DBMS • Transaction Management • Chapter 4 • © EDUKOSAL. For learning use.
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.

Post a Comment

0 Comments