0% found this document useful (0 votes)
22 views12 pages

Bank Transfer Transaction Control Simulation

The document outlines an assignment on simulating a bank transfer between two accounts using transactions, focusing on transaction properties, concurrency control, and query optimization. It discusses transaction processing, properties such as atomicity, consistency, isolation, and durability, as well as concurrency control techniques like lock-based protocols and optimistic concurrency control. The document concludes with a Java implementation for managing bank account transactions using MySQL.

Uploaded by

Vaibhav Chate
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views12 pages

Bank Transfer Transaction Control Simulation

The document outlines an assignment on simulating a bank transfer between two accounts using transactions, focusing on transaction properties, concurrency control, and query optimization. It discusses transaction processing, properties such as atomicity, consistency, isolation, and durability, as well as concurrency control techniques like lock-based protocols and optimistic concurrency control. The document concludes with a Java implementation for managing bank account transactions using MySQL.

Uploaded by

Vaibhav Chate
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

Assignment No:9

Title: Transaction Implementation and Concurrency Control

Problem Statement: Simulate a bank transfer between two accounts using transactions.

Course Objective: To become familiar with transactions, concurrency, and query optimization.

Course Outcome: Demonstrate transaction properties, concurrency control, and query


optimization methods for efficient database performance.

Tools Required:.Java, Eclipse, MySql

Theory:

1. Transaction processing:
 Transaction in Database Management Systems (DBMS) can be defined as a set of
logically related operations.
 It is the result of a request made by the user to access the contents of the database and
perform operations on it.
 It consists of various operations and has various states in its completion journey.
 It also has some specific properties that must be followed to keep the database consistent.
1.1 Operations of Transaction
A user can make different types of requests to access and modify the contents of a database. So,
we have different types of operations relating to a transaction. They are discussed as follows:
 Read(X): A read operation is used to read the value of X from the database and store it in
a buffer in the main memory for further actions such as displaying that value.
 Write(X): A write operation is used to write the value to the database from the buffer in
the main memory. For a write operation to be performed, first a read operation is
performed to bring its value in buffer, and then some changes are made to it, e.g. some set
of arithmetic operations are performed on it according to the user’s request, then to store
the modified value back in the database, a write operation is performed.
 Commit: This operation in transactions is used to maintain integrity in the database. Due
to some failure of power, hardware, or software, etc., a transaction might get interrupted
before all its operations are completed.

2. Property of Transaction
2.1. Atomicity
It states that all operations of the transaction take place at once if not, the transaction is aborted.
There is no midway, i.e., the transaction cannot occur partially. Each transaction is treated as one
unit and either run to completion or is not executed at all.
Atomicity involves the following two operations:
Abort: If a transaction aborts then all the changes made are not visible.
Commit: If a transaction commits then all the changes made are visible.

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 1


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

Example: Let's assume that following transaction T consisting of T1 and T2. A consists of Rs
600 and B consists of Rs 300. Transfer Rs 100 from account A to account B.

After completion of the transaction, A consists of Rs 500 and B consists of Rs 400.


If the transaction T fails after the completion of transaction T1 but before completion of
transaction T2, then the amount will be deducted from A but not added to B. This shows the
inconsistent database state. In order to ensure correctness of database state, the transaction must
be executed in entirety.
2.2. Consistency
A transaction must bring the database from one valid state to another valid state.
It ensures all integrity constraints, rules, and relationships are preserved.
Example: After a transfer, the total balance across all accounts must remain unchanged.
2.3. Isolation
Multiple transactions can occur concurrently, but they should not interfere with each other.
Each transaction must behave as if it is executed alone in the system.
Example: If two users transfer money at the same time, their transactions should not overwrite or
corrupt each other’s data.
2.4. Durability
Once a transaction is committed, the changes are permanent in the database, even in case of
system failures (e.g., power loss or crash).
Example: Once money is successfully transferred, the record remains saved even if the system
shuts down immediately after.

3. Schedule
 A series of operation from one transaction to another transaction is known as schedule.
 It is used to preserve the order of the operation in each of the individual transaction.
3.1 Serial Schedule
 The serial schedule is a type of schedule where one transaction is executed completely
before starting another transaction.

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 2


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

 In the serial schedule, when the first transaction completes its cycle, then the next
transaction is executed.
For example: Suppose there are two transactions T1 and T2 which have some operations. If
it has no interleaving of operations, then there are the following two possible outcomes:
 Execute all the operations of T1 which was followed by all the operations of T2.
 Execute all the operations of T1 which was followed by all the operations of T2.
 In the given (a) figure, Schedule A shows the serial schedule where T1 followed by T2.
 In the given (b) figure, Schedule B shows the serial schedule where T2 followed by T1.

3.2 Non-serial Schedule


 If interleaving of operations is allowed, then there will be non-serial schedule.
 It contains many possible orders in which the system can execute the individual
operations of the transactions.
 In the given figure (c) and (d), Schedule C and Schedule D are the non-serial schedules. It
has interleaving of operations.
3.3 Serializable schedule
 The serializability of schedules is used to find non-serial schedules that allow the
transaction to execute concurrently without interfering with one another.
 It identifies which schedules are correct when executions of the transaction have
interleaving of their operations.
 A non-serial schedule will be serializable if its result is equal to the result of its
transactions executed serially.

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 3


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

Suppose the current values of accounts A and B are $1000 and $2000, respectively. Suppose also
that the two transactions are executed one at a time in the order T1 followed by T2. The final
values of accounts A and B, after the execution in schedule 1 takes place, are $855 and $2145,
respectively. Thus, the total amount of money in accounts A and B— that is, the sum A + B—is
preserved after the execution of both transactions
Similarly, if the transactions are executed one at a time in the order T2 followed by T1, then the
corresponding execution sequence is that of Figure 2. Again, as expected, the sum A + B is
preserved, and the final values of accounts A and B are $850 and $2150, respectively. The
execution sequences just described are called schedules.
Suppose that the two transactions are executed concurrently shown in Figure 3. After this
execution takes place, we arrive at the same state as the one in which the transactions are
executed serially in the order T1 followed by T2. The sum A + B is indeed preserved

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 4


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

We can ensure consistency of the database under concurrent execution by making sure that any
schedule that is executed has the same effect as a schedule that could have occurred without any
concurrent execution. That is, the schedule should, in some sense, be equivalent to a serial
schedule. Such schedules are called serializable schedules.

4. Concurrency Control Techniques


4.1 Lock-Based Protocols
 One way to ensure isolation is to require that data items be accessed in a mutually
exclusive manner; that is, while one transaction is accessing a data item, no other
transaction can modify that data item.
 The most common method used to implement this requirement is to allow a transaction to
access a data item only if it is currently holding a lock on that item.

4.1.1 Locks
 There are various modes in which a data item may be locked.
1. Shared. If a transaction Ti has obtained a shared-mode lock (denoted by S) on item Q, then Ti
can read, but cannot write, Q.
2. Exclusive. If a transaction Ti has obtained an exclusive-mode lock (denoted by X) on item Q,
then Ti can both read and write Q.
We require that every transaction request a lock in an appropriate mode on data item Q,
depending on the types of operations that it will perform on Q. The transaction makes the request
to the concurrency-control manager. The transaction can proceed with the operation only after
the concurrency-control manager grants the lock to the transaction. The use of these two lock
modes allows multiple transactions to read a data item but limits write access to just one
transaction at a time.

4.2 The Two-Phase Locking Protocol


One protocol that ensures serializability is the two-phase locking protocol.
This protocol requires that each transaction issue lock and unlock requests in two phases:
1. Growing phase. A transaction may obtain locks, but may not release any lock.
2. Shrinking phase. A transaction may release locks, but may not obtain any new locks.
Initially, a transaction is in the growing phase. The transaction acquires locks as needed. Once
the transaction releases a lock, it enters the shrinking phase, and it can issue no more lock
requests.

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 5


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

 The point in the schedule where the transaction has obtained its final lock (the end of its
growing phase) is called the lock point of the transaction. Now, transactions can be
ordered according to their lock points—
 this ordering is, in fact, a serializability ordering for the transactions.

4.3 Timestamp-Based Protocols


 Timestamps With each transaction Ti in the system, we associate a unique fixed
timestamp, denoted by TS(Ti).
 This timestamp is assigned by the database system before the transaction Ti starts
execution. If a transaction Ti has been assigned timestamp TS(Ti), and a new transaction
Tj enters the system, then TS(Ti) < TS(Tj).
 There are two simple methods for implementing this scheme:
1. Use the value of the system clock as the timestamp; that is, a transaction’s timestamp is
equal to the value of the clock when the transaction enters the system.
2. Use a logical counter that is incremented after a new timestamp has been assigned; that
is, a transaction’s timestamp is equal to the value of the counter when the transaction
enters the system.
 The timestamps of the transactions determine the serializability order.
 Thus, if TS(Ti) < TS(Tj), then the system must ensure that the produced schedule is
equivalent to a serial schedule in which transaction Ti appears before transaction Tj .
 To implement this scheme, we associate with each data item Q two timestamp values:
• W-timestamp(Q) denotes the largest timestamp of any transaction that executed write(Q)
successfully.
• R-timestamp(Q) denotes the largest timestamp of any transaction that executed read(Q)
successfully.

4.3.1 The Timestamp-Ordering Protocol


The timestamp-ordering protocol ensures that any conflicting read and write operations are
executed in timestamp order. This protocol operates as follows:
1. Suppose that transaction Ti issues read(Q).
• If TS(Ti) < W-timestamp(Q), then Ti needs to read a value of Q that was already
overwritten. Hence, the read operation is rejected, and Ti is rolled back.
• If TS(Ti) ≥ W-timestamp(Q), then the read operation is executed, and R-timestamp(Q) is
set to the maximum of R-timestamp(Q) and TS(Ti).
2. Suppose that transaction Ti issues write(Q).
• If TS(Ti) < R-timestamp(Q), then the value of Q that Ti is producing was needed
previously, and the system assumed that that value would never be produced. Hence, the
system rejects the write operation and rolls Ti back.
• If TS(Ti) < W-timestamp(Q), then Ti is attempting to write an obsolete value of Q.
Hence, the system rejects this write operation and rolls Ti back. c. Otherwise, the system
executes the write operation and sets W-timestamp(Q) to TS(Ti).

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 6


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

4.4 Multiversion Timestamp Ordering


 The timestamp-ordering protocol can be extended to a multiversion protocol.
 With each transaction Ti in the system, we associate a unique static timestamp, denoted
by TS(Ti).
 The database system assigns this timestamp before the transaction starts execution.
 With each data item Q, a sequence of versions is associated.
 Each version Qk contains three data fields:
 Content is the value of version Qk .
 W-timestamp(Qk ) is the timestamp of the transaction that created version Qk .
 R-timestamp(Qk ) is the largest timestamp of any transaction that successfully read
version Qk .
 A transaction—say, Ti—creates a new version Qk of data item Q by issuing a write(Q)
operation.
 The content field of the version holds the value written by Ti .
 The system initializes the W-timestamp and R-timestamp to TS(Ti).
 It updates the R-timestamp value of Qk whenever a transaction Tj reads the content of Qk
, and R-timestamp(Qk ) < TS(Tj).
 The multiversion timestamp-ordering scheme presented next ensures serializability.
 The scheme operates as follows: Suppose that transaction Ti issues a read(Q) or write(Q)
operation.
 Let Qk denote the version of Q whose write timestamp is the largest write timestamp less
than or equal to TS(Ti).

4.5 Optimistic Concurrency Control schemes


 The optimistic approach is based on the assumption that the majority of the database
operations do not conflict.
 The optimistic approach requires neither locking nor time stamping techniques.
 Instead, a transaction is executed without restrictions until it is committed.
 Using an optimistic approach, each transaction moves through 2 or 3 phases, referred to
as read, validation and write.
1. (i) During read phase, the transaction reads the database, executes the needed
computations and makes the updates to a private copy of the database values. All update
operations of the transactions are recorded in a temporary update file, which is not
accessed by the remaining transactions.
2. (ii) During the validation phase, the transaction is validated to ensure that the changes
made will not affect the integrity and consistency of the database. If the validation test is
positive, the transaction goes to a write phase. If the validation test is negative, he
transaction is restarted and the changes are discarded.
3. (iii) During the write phase, the changes are permanently applied to the database.

Conclusion: Hence, we have successfully simulate a bank transfer between two accounts using
transactions.

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 7


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

Output:
package [Link];

/*
* CREATE TABLE bank_account (
-> id INT PRIMARY KEY,
-> name VARCHAR(50),
-> balance DOUBLE
-> );
INSERT INTO bank_account (id, name, balance) VALUES (1, 'nilesh',1000.00), (2,'keshav',
500.00),(3,'sunil',300);
*/
import [Link].*;
class Bank
{
private final String url = "jdbc:mysql://localhost:3309/test";
private final String user = "root";
private final String password = "root";

// Show current balance of all accounts


public void showBalances(String message)
{
[Link]("\n=== " + message + " ===");
try (Connection conn = [Link](url, user, password);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT id, name, balance FROM bank_account
ORDER BY id"))
{

while ([Link]())
{
[Link]("Account " + [Link]("name") +
" (ID " + [Link]("id") + ") Balance: ₹" + [Link]("balance"));
}
}
catch (SQLException e)
{
[Link]();
}
}

// Synchronized transfer method with transaction


public synchronized void transfer(int fromId, int toId, double amount)
{
Connection conn = null;
try
Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 8
Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

{
conn = [Link](url, user, password);
[Link](false); // Start transaction

// Lock accounts and read balances


double fromBal = 0, toBal = 0;

Statement stmt1 = [Link]();


ResultSet rs1 = [Link]("SELECT balance FROM bank_account WHERE
id = " + fromId + " FOR UPDATE");
if ([Link]())
fromBal = [Link]("balance");
[Link]();
[Link]();

Statement stmt2 = [Link]();


ResultSet rs2 = [Link]("SELECT balance FROM bank_account WHERE
id = " + toId + " FOR UPDATE");
if ([Link]())
toBal = [Link]("balance");
[Link]();
[Link]();

if (fromBal >= amount)


{
fromBal -= amount;
toBal += amount;

Statement stmt3 = [Link]();


[Link]("UPDATE bank_account SET balance = " + fromBal + "
WHERE id = " + fromId);
[Link]("UPDATE bank_account SET balance = " + toBal + "
WHERE id = " + toId);
[Link]();

[Link]("Transferred ₹" + amount + " from ID " + fromId + " to ID " +


toId);
[Link]();
}
else
{
[Link]("Insufficient balance in ID " + fromId);
[Link]();
}

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 9


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

catch (Exception e)
{
[Link]();
try
{
if (conn != null) [Link]();
}
catch (SQLException se)
{
[Link]();
}
}
finally
{
try
{
if (conn != null) [Link]();
}
catch (SQLException se)
{
[Link]();
}
}
}
}

class BankThread extends Thread


{
Bank bank;
int fromId, toId;
double amount;

public BankThread(Bank bank, int fromId, int toId, double amount)


{
[Link] = bank;
[Link] = fromId;
[Link] = toId;
[Link] = amount;
}

public void run()


{
[Link](fromId, toId, amount);
}
}

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 10


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

public class BankTransferMain


{
public static void main(String[] args)
{
Bank bank = new Bank();

// Show initial balances


[Link]("Initial Balances");

// Run transfers in threads


BankThread t1 = new BankThread(bank, 1, 2, 500); // A → B
BankThread t2 = new BankThread(bank, 2, 3, 300); // B → C

[Link]();
[Link]();

try
{
[Link]();
[Link]();
}
catch (InterruptedException e)
{
[Link]();
}

// Show final balances


[Link]("Final Balances");
}
}
Output:
=== Initial Balances ===
Account nilesh (ID 1) Balance: ₹3300.0
Account keshav (ID 2) Balance: ₹300.0
Account sunil (ID 3) Balance: ₹1500.0
Account mohan (ID 4) Balance: ₹99999.0
Transferred ₹500.0 from ID 1 to ID 2
Transferred ₹300.0 from ID 2 to ID 3

=== Final Balances ===


Account nilesh (ID 1) Balance: ₹2800.0
Account keshav (ID 2) Balance: ₹500.0
Account sunil (ID 3) Balance: ₹1800.0
Account mohan (ID 4) Balance: ₹99999.0
Database:

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 11


Subject Name- CI2012: Database Management Systems Class: SY-CSAI-E Roll no: 01

Computer Science and Engineering (Artificial Intelligence), VIT Pune. Page 12

Common questions

Powered by AI

Rollback mechanisms can lead to challenges such as increased resource usage due to maintaining prior states, potential cascades of rollbacks affecting many transactions, and possible data inconsistencies from partial operations. These can be mitigated by using efficient logging strategies like write-ahead logging, implementing a robust deadlock detection mechanism, and using techniques like savepoints to minimize extensive rollbacks .

Timestamp-based protocols assign unique timestamps to each transaction to control the serializability order. Transactions execute operations based on their timestamps, where Ti must execute before Tj if TS(Ti) < TS(Tj). The system uses timestamps associated with data items to enforce this order, rejecting operations that violate the timestamp condition, such as rolling back those that try to read or write outdated data .

The two-phase locking protocol ensures serializability by issuing lock and unlock requests in two distinct phases: the growing phase, where a transaction can acquire but not release locks, and the shrinking phase, where it can release but not acquire new locks. By following these phases, transactions can be ordered according to their lock points, which reflects a serial order that is conflict-free .

In the bank transfer simulation, transaction isolation is achieved through the use of synchronized methods, which prevent concurrent transfer modifications to the same account data. By locking the accounts during balance checks and updates, it ensures that no other transaction can access these data items simultaneously, maintaining isolation and preventing inconsistencies .

The optimistic concurrency control approach is based on the assumption that most transactions do not conflict. It has three stages: read, where transactions read and make changes to a private copy; validation, which checks for conflicts and ensures integrity; and write, where confirmed changes are applied to the database. Unlike locking and timestamp methods, it imposes minimal restrictions during transaction execution and only checks for conflicts before committing changes .

The atomicity property ensures that all operations of a transaction are completed, or none at all, thereby maintaining database consistency. If a transaction is interrupted due to power, hardware, or software failures, atomicity calls for aborting the transaction and rolling back any changes made, so no partial update results in an inconsistent state .

The example of transferring money between accounts illustrates the importance of maintaining atomicity and consistency, as any interruption during the transaction—such as after the withdrawal but before the deposit—is avoided. Atomicity ensures that all operations within the transaction Must complete successfully or none do, preventing partial transactions that could lead to data inconsistencies, such as money being debited without crediting another account .

Multiversion concurrency control ensures serializability by maintaining multiple versions of data items. Each version has associated read and write timestamps, ensuring that transactions operate on consistent snapshots of data. A new version is created with each successful write operation. The protocol guarantees serializability by allowing reads to occur from the correct version according to the transaction's timestamp order .

A schedule is serializable if its result is the same as that of its transactions executed serially. This condition is important for concurrency control as it ensures that transactions executed concurrently do not interfere with each other, preserving consistency and integrity of the database. Serializable schedules achieve the effects of serial execution and are crucial in preventing anomalies like lost updates, dirty reads, and inconsistent analysis .

Lock-based protocols ensure isolation by making data items mutually exclusive so that, while a transaction accesses a data item, no other transaction can modify it. The types of locks used are shared locks, which allow multiple transactions to read a data item, and exclusive locks, which allow only one transaction to read and write a data item at a time .

You might also like