implement TODOs

This commit is contained in:
2026-06-10 06:53:34 +03:30
parent fa95f2ebeb
commit 2d457d8c0f
8 changed files with 114 additions and 38 deletions
@@ -1,18 +1,15 @@
package dev.banking.model;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class BankAccount {
private final int accountId;
private long balance;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
/*
* Students may introduce additional fields
* such as:
* - Lock / ReentrantLock
* - ReadWriteLock
* - Object monitor
* - etc.
*/
public BankAccount(int accountId, long initialBalance) {
this.accountId = accountId;
@@ -23,40 +20,36 @@ public class BankAccount {
return accountId;
}
/*
* TODO:
* Return the current balance in a thread-safe way.
*
* Requirements:
* - Must be safe under concurrent reads/writes
* - Should not block unnecessarily if using read/write locks
*/
public long getBalance() {
throw new UnsupportedOperationException("TODO: implement thread-safe balance read");
lock.readLock().lock();
try {
return balance;
}
finally {
lock.readLock().unlock();
}
}
/*
* TODO:
* Increase balance atomically.
*
* Requirements:
* - Must not lose updates under concurrency
*/
public void deposit(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
lock.writeLock().lock();
try {
balance += amount;
}
finally {
lock.writeLock().unlock();
}
}
/*
* TODO:
* Decrease balance atomically.
*
* Requirements:
* - Must not cause race conditions
* - Negative balance handling is NOT required unless you decide
* to extend the system (optional)
*/
public void withdraw(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
lock.writeLock().lock();
try {
balance -= amount;
}
finally {
lock.writeLock().unlock();
}
}
/*
@@ -73,6 +66,21 @@ 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 = this.accountId < target.accountId ? this : target;
BankAccount second = this.accountId > target.accountId ? this : target;
first.lock.writeLock().lock();
try {
second.lock.writeLock().lock();
try {
this.balance -= amount;
target.balance += amount;
} finally {
second.lock.writeLock().unlock();
}
}
finally{
first.lock.writeLock().unlock();
}
}
}