Last active
July 1, 2020 14:58
-
-
Save mcculley/de7d8182a283a24c8625bdf9b552d39c to your computer and use it in GitHub Desktop.
A simple example of a bank account model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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