Skip to content

Instantly share code, notes, and snippets.

@patriknw
Created April 26, 2011 12:12
Show Gist options
  • Save patriknw/942156 to your computer and use it in GitHub Desktop.
Save patriknw/942156 to your computer and use it in GitHub Desktop.
Agent with STM
package agent
import akka.agent.Agent
import akka.stm._
object AgentStmSample {
def transfer(from: Agent[Int], to: Agent[Int], amount: Int): Boolean = {
atomic {
if (from.get < amount) false
else {
from send (_ - amount)
to send (_ + amount)
true
}
}
}
def run() {
val from = Agent(100)
val to = Agent(20)
val ok = transfer(from, to, 50)
if (ok) println("New balance, from: %s, to: %s".format(from.await, to.await))
else println("Not enough money, transfer cancelled")
from.close()
to.close()
}
def main(args: Array[String]) {
run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment