Sunday, 5 July 2009

Actors & Concurrency

Actors are the first thing I've found where Scala definently kicks Java's ass.

We dont use 'Synchronized' anymore. Instead each 'Actor' has a sort of 'mail box' or 'to do list' that other processes can call either Synchronously or Asynchronously.

code:


package scalaexperiment

import scala.actors._
import Actor._

case class SayHi
case class SayThis(s : String)
case class GetActorStatus

object Actors {
def main(args : Array[String]) : Unit = {
val man = new Man1

(0 to 3).foreach( a => {
man ! SayHi //Asynchronous calls
man ! SayThis("gobblydgook "+a)
man ! Actors
})

println("I am going to wait here...")
val count = man !? GetActorStatus //Sychronous call
println("....For you to tell me how many times you were called: "+count)
}
}

class Man1 extends Actor {
val s = "From Actor> "
var count = 0;
def act = loop {
react {
count += 1
doOptions
}
}

def doOptions : PartialFunction[Any, Unit] = {
case GetActorStatus => reply(count)
case SayHi => println(s+"hi")
case SayThis(a) => println(s + a)
case _ => println(s+"Dont know what you asked me to say ")
}
this.start
}


Tip: Dont forget to call 'start' on your Actors.

Additional:
! = Asynch call
!? = Synch call (wait for me!)
!! = Asynch call that returns a Future[T] value
reactWithin(n) = react within n milliseconds.
!?(n, param) = wait n seconds for result.

No comments:

Post a comment