Created
July 5, 2011 21:37
-
-
Save dwhitney/1066021 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class Account(val accountNo: String, beginningBalance: Int){ | |
| private var _balance = beginningBalance | |
| def balance = this.synchronized{ _balance } | |
| def credit(amount: Int) = this.synchronized{ _balance = _balance + amount } | |
| def debit(amount: Int) = this.synchronized { _balance = _balance - amount } | |
| } | |
| object Bank{ | |
| val accounts = Map("from" -> new Account("from", 500), "to" -> new Account("to", 500) ) | |
| def transfer(fromNo: String, toNo: String, amount: Int): Unit = { | |
| val (from, to) = (accounts(fromNo), accounts(toNo)) | |
| val (lockOne, lockTwo) = if(from.accountNo < to.accountNo) (from, to) else (to, from) | |
| lockOne.synchronized{ | |
| lockTwo.synchronized{ | |
| if(from.balance > amount){ | |
| to.credit(amount) | |
| from.debit(amount) | |
| } | |
| } | |
| } | |
| } | |
| def main(args: Array[String]): Unit = { | |
| import java.util.concurrent._ | |
| import scala.util.Random._ | |
| val executor = Executors.newFixedThreadPool(2) | |
| for(_ <- 1 to 10000) yield { | |
| executor.submit(new Runnable(){ | |
| def run = { | |
| if(nextInt(2) % 2 == 0) Bank.transfer("from", "to", nextInt(50)) | |
| else Bank.transfer("to", "from", nextInt(50)) | |
| } | |
| }) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment