Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

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