Complete the project
This commit is contained in:
@@ -1,10 +1,16 @@
|
||||
package dev.banking.model;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
public class BankAccount {
|
||||
|
||||
private final int accountId;
|
||||
private long balance;
|
||||
|
||||
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
|
||||
private final ReentrantLock transferLock = new ReentrantLock();
|
||||
|
||||
/*
|
||||
* Students may introduce additional fields
|
||||
* such as:
|
||||
@@ -32,7 +38,12 @@ public class BankAccount {
|
||||
* - Should not block unnecessarily if using read/write locks
|
||||
*/
|
||||
public long getBalance() {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe balance read");
|
||||
rwLock.readLock().lock();
|
||||
try {
|
||||
return balance;
|
||||
} finally {
|
||||
rwLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -43,7 +54,12 @@ public class BankAccount {
|
||||
* - Must not lose updates under concurrency
|
||||
*/
|
||||
public void deposit(long amount) {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe deposit");
|
||||
rwLock.writeLock().lock();
|
||||
try {
|
||||
balance += amount;
|
||||
} finally {
|
||||
rwLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -56,7 +72,12 @@ public class BankAccount {
|
||||
* to extend the system (optional)
|
||||
*/
|
||||
public void withdraw(long amount) {
|
||||
throw new UnsupportedOperationException("TODO: implement thread-safe withdraw");
|
||||
rwLock.writeLock().lock();
|
||||
try {
|
||||
balance -= amount;
|
||||
} finally {
|
||||
rwLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -73,6 +94,29 @@ 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;
|
||||
BankAccount second;
|
||||
|
||||
if (this.getAccountId() < target.getAccountId()) {
|
||||
first = this;
|
||||
second = target;
|
||||
} else {
|
||||
first = target;
|
||||
second = this;
|
||||
}
|
||||
|
||||
first.transferLock.lock();
|
||||
|
||||
try {
|
||||
second.transferLock.lock();
|
||||
try {
|
||||
first.balance -= amount;
|
||||
target.balance += amount;
|
||||
} finally {
|
||||
second.transferLock.unlock();
|
||||
}
|
||||
} finally {
|
||||
first.transferLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user