Created
April 26, 2011 12:12
-
-
Save patriknw/942156 to your computer and use it in GitHub Desktop.
Agent with STM
This file contains 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
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