Skip to content

Instantly share code, notes, and snippets.

@dwhitney
Created July 6, 2011 15:35
Show Gist options
  • Select an option

  • Save dwhitney/1067535 to your computer and use it in GitHub Desktop.

Select an option

Save dwhitney/1067535 to your computer and use it in GitHub Desktop.
import scala.concurrent.stm._
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 accountsRef = Ref(Map("from" -> new Account("from", 500), "to" -> new Account("to", 500) ))
def transfer(fromNo: String, toNo: String, amount: Int): Unit = {
atomic{ implicit t =>
var accounts = accountsRef()
val (from, to) = (accounts(fromNo), accounts(toNo))
if(from.balance > amount){
to.credit(amount)
from.debit(amount)
accounts = accounts + (to.accountNo -> to)
accounts = accounts + (from.accountNo -> from)
accountsRef() = accounts
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment