This commit is contained in:
2026-06-15 01:27:43 +04:30
parent fa95f2ebeb
commit 783359667a
9 changed files with 274 additions and 9 deletions
@@ -1,9 +1,14 @@
package dev.banking.model;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private final int accountId;
private long balance;
private ReentrantLock lock = new ReentrantLock();
/*
* Students may introduce additional fields
@@ -31,8 +36,8 @@ 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 synchronized long getBalance() { //??????????????????????????/?
return balance;
}
/*
@@ -42,8 +47,8 @@ public class BankAccount {
* Requirements:
* - Must not lose updates under concurrency
*/
public void deposit(long amount) {
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
public synchronized void deposit(long amount) {
balance += amount;
}
/*
@@ -55,8 +60,8 @@ public class BankAccount {
* - 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");
public synchronized void withdraw(long amount) {
balance -= amount;
}
/*
@@ -73,6 +78,14 @@ 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 = target.getAccountId() < accountId ? target : this ;
BankAccount second = target.getAccountId() < accountId ? this : target ;
synchronized (first) {
synchronized (second) {
target.deposit(amount);
this.withdraw(amount);
}
}
}
}