Develop #1

Open
farnam_jhn wants to merge 2 commits from develop into main
Showing only changes of commit 2f1a3bee23 - Show all commits
@@ -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();
}
}
}