Skip to content

Instantly share code, notes, and snippets.

object Circle{
def circleAtOrigin = Circle(0, 0, _: Double)
}
case class Circle(x: Double, y: Double, radius: Double)
class Account(val accountNo: String, var balance: Int){
def credit(amount: Int) = balance = balance + amount
def debit(amount: Int) = 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 = {
def main(args: Array[String]): Unit = {
import java.util.concurrent._
import scala.util.Random._
val executor = Executors.newFixedThreadPool(2)
for(_ <- 1 to 10000){
executor.submit(new Runnable(){
def run = {
if(nextInt(2) % 2 == 0) Bank.transfer("from", "to", nextInt(50))
else Bank.transfer("to", "from", nextInt(50))
}
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) )
import scala.actors._
import Actor._
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 balance = (from !? Balance).asInstanceOf[Int]
import scala.actors._
import Actor._
object Bank extends Actor{
private var accounts = Map("from" -> Account("from", 500), "to" -> Account("to", 500) )
def act = {
loop{
react{
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) ))
atomic{ implicit t =>
var accounts = accountsRef()
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
applyTransferFees()
}
}
val shouldApplyTransferFees: Boolean = atomic{ implicit t =>
var accounts = accountsRef()
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
true
}else false
}
private val map = new java.util.HashMap[String, Account]()
map.put("from", Account("from", 500))
map.put("to", Account("to", 500))
val accountsRef = Ref(map)
def transfer(fromNo: String, toNo: String, amount: Int): Unit = {
atomic{ implicit t =>
var accounts = accountsRef()
val (from, to) = (accounts.get(fromNo), accounts.get(toNo))