Implement thread-safe BankAccount operations
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
package dev.banking.model;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class BankAccount {
|
||||
|
||||
@@ -13,7 +14,7 @@ public class BankAccount {
|
||||
* - Object monitor
|
||||
* - etc.
|
||||
*/
|
||||
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
public BankAccount(int accountId, long initialBalance) {
|
||||
this.accountId = accountId;
|
||||
this.balance = initialBalance;
|
||||
@@ -32,7 +33,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 +50,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 +69,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 +92,28 @@ 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 lock1;
|
||||
BankAccount lock2;
|
||||
|
||||
if (this.accountId < target.accountId){
|
||||
lock1 = this;
|
||||
lock2 = target;
|
||||
}
|
||||
else{
|
||||
lock1 = target;
|
||||
lock2 = this;
|
||||
}
|
||||
|
||||
lock1.lock.lock();
|
||||
lock2.lock.lock();
|
||||
|
||||
try {
|
||||
this.balance -= amount;
|
||||
target.balance += amount;
|
||||
}
|
||||
finally{
|
||||
lock2.lock.unlock();
|
||||
lock1.lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user