implement bankAccount + bonus

This commit is contained in:
Matin
2026-06-14 04:07:46 +04:30
parent fa95f2ebeb
commit 52d5665fc0
7 changed files with 133 additions and 6 deletions
@@ -1,10 +1,14 @@
package dev.banking.model;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Condition;
public class BankAccount {
private final int accountId;
private long balance;
private final ReentrantLock lock = new ReentrantLock();
private final Condition sufficientFunds = lock.newCondition();
/*
* Students may introduce additional fields
* such as:
@@ -31,8 +35,16 @@ public class BankAccount {
* - 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");
public long getBalance()
{
lock.lock();
try{
return this.balance ;
}finally {
lock.unlock();
}
}
/*
@@ -42,8 +54,16 @@ public class BankAccount {
* Requirements:
* - Must not lose updates under concurrency
*/
public void deposit(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
if (amount <= 0) return;
lock.lock();
try {
this.balance += amount ;
}finally {
lock.unlock();
}
}
/*
@@ -56,7 +76,21 @@ public class BankAccount {
* to extend the system (optional)
*/
public void withdraw(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
lock.lock();
try {
while (this.balance < amount )
{
try {
sufficientFunds.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
this.balance -= amount ;
}finally {
lock.unlock();
}
}
/*
@@ -73,6 +107,30 @@ public class BankAccount {
* - Or tryLock with retry strategy
*/
public void transfer(BankAccount target, long amount) {
throw new UnsupportedOperationException("TODO: implement atomic deadlock-free transfer");
if (target == null || amount <= 0 || target.accountId == this.accountId ) return;
BankAccount firstAccount ;
BankAccount secondAccount ;
if (this.accountId < target.accountId )
{
firstAccount = this ;
secondAccount = target ;
}
else {
firstAccount = target ;
secondAccount = this ;
}
firstAccount.lock.lock();
try {
secondAccount.lock.lock();
try {
this.balance -= amount ;
target.balance += amount ;
}finally {
secondAccount.lock.unlock();
}
}finally {
firstAccount.lock.unlock();
}
}
}