Skip to content

Instantly share code, notes, and snippets.

@mcculley
Last active July 1, 2020 14:58
Show Gist options
  • Save mcculley/de7d8182a283a24c8625bdf9b552d39c to your computer and use it in GitHub Desktop.
Save mcculley/de7d8182a283a24c8625bdf9b552d39c to your computer and use it in GitHub Desktop.
A simple example of a bank account model
public class Account {
public static class InsufficientFundsException extends Exception {
}
private int balance;
public synchronized void transferTo(final int amount, final Account destination) throws InsufficientFundsException {
synchronized (destination) {
withdraw(amount);
destination.deposit(amount);
}
}
public synchronized void withdraw(final int amount) throws InsufficientFundsException {
if (sufficientFunds(amount)) {
balance -= amount;
} else {
throw new InsufficientFundsException();
}
}
public synchronized void deposit(final int amount) {
balance += amount;
}
public synchronized int balance() {
return balance;
}
private boolean sufficientFunds(final int amount) {
return balance >= amount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment