From 2f1a3bee23aedeb1979e29b9da78c5d82c9e4ff4 Mon Sep 17 00:00:00 2001 From: Farnam Jahangard Date: Thu, 11 Jun 2026 17:53:27 +0330 Subject: [PATCH] implemented methods in BankAccount.java passed all the tests --- .../java/dev/banking/model/BankAccount.java | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/src/main/java/dev/banking/model/BankAccount.java b/src/main/java/dev/banking/model/BankAccount.java index 745ede2..fbfa154 100644 --- a/src/main/java/dev/banking/model/BankAccount.java +++ b/src/main/java/dev/banking/model/BankAccount.java @@ -1,10 +1,14 @@ package dev.banking.model; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + public class BankAccount { private final int accountId; private long balance; - + private final Lock lock = new ReentrantLock(); /* * Students may introduce additional fields * such as: @@ -32,7 +36,13 @@ 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,13 @@ 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 +72,13 @@ 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,19 @@ 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.getAccountId() > target.getAccountId() ? target : this; + BankAccount second = this.getAccountId() > target.getAccountId() ? this : target; + + first.lock.lock(); + second.lock.lock(); + try { + this.balance -= amount; + target.balance += amount; + } + finally { + second.lock.unlock(); + first.lock.unlock(); + } + } } \ No newline at end of file