HW 09
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user