Completion of the specified parts

This commit is contained in:
2026-07-17 23:02:03 +03:30
parent fa95f2ebeb
commit 86882ca197
2 changed files with 96 additions and 4 deletions
@@ -4,6 +4,7 @@ public class BankAccount {
private final int accountId;
private long balance;
private final ReentrantLock lock = new ReentrantLock();
/*
* Students may introduce additional fields
@@ -32,7 +33,16 @@ public class BankAccount {
* - Should not block unnecessarily if using read/write locks
*/
public long getBalance() {
throw new UnsupportedOperationException("TODO: implement thread-safe balance read");
lock.lock();
try{
return balance;
}finally {
lock.unlock();
}
}
/*
@@ -43,7 +53,14 @@ public class BankAccount {
* - Must not lose updates under concurrency
*/
public void deposit(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
lock.lock();
try{
balance+=amount;
}finally {
lock.unlock();
}
}
/*
@@ -56,7 +73,12 @@ public class BankAccount {
* to extend the system (optional)
*/
public void withdraw(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
lock.lock();
try{
balance-=amount;
}finally {
lock.unlock();
}
}
/*
@@ -73,6 +95,33 @@ public class BankAccount {
* - Or tryLock with retry strategy
*/
public void transfer(BankAccount target, long amount) {
throw new UnsupportedOperationException("TODO: implement atomic deadlock-free transfer");
BankAccount first;
BankAccount second;
if (this == target) {
return;
}
if (this.getAccountId() < target.getAccountId()) {
first = this;
second = target;
} else {
first = target;
second = this;
}
first.lock.lock();
try {
second.lock.lock();
try {
this.balance -= amount;
target.balance += amount;
} finally {
second.lock.unlock();
}
} finally {
first.lock.unlock();
}
}
}