I'm trying to reproduce this example. Everything compiles, but when I run it, all my results l开发者_JAVA技巧ook like this:
scala> NameResolver ! ("www.scala-lang.org", self)
scala> self.receiveWithin(0) { case x => x }
res0: Any = TIMEOUT // and not Some(www.scala-lang.org/128.178.154.102)
scala> NameResolver ! ("wwwwww.scala-lang.org", self)
scala> self.receiveWithin(0) { case x => x }
res1: Any = TIMEOUT // and not None
Here is my example:
import scala.actors._
import scala.actors.Actor._
case class Plus(x: Int, y: Int)
val concurrentCalculator = actor {
while(true)
receive {
case Plus(x, y) => println(x + y)
case (Plus(x, y), caller: Actor) => caller ! (x + y)
}
}
scala> concurrentCalculator ! Plus(2,3)
5
scala> concurrentCalculator ! (Plus(2,3), self)
scala> self.receiveWithin(1000) { case x => x }
res0: Any = TIMEOUT // WTF?
So why am I getting a TIMEOUT
instead of a valid result?
You can check that self
returns different values on different calls not within a code block, due to the way Scala REPL works (every expression to be evaluated is compiled into a separate class):
scala> self
res3: scala.actors.Actor = scala.actors.ActorProxy@1bb0ff0
scala> self
res4: scala.actors.Actor = scala.actors.ActorProxy@46530
In one block of code it will work even if it isn't explicitly declared as an actor:
scala> {
| concurrentCalculator ! (Plus(2,3), self)
| self.receiveWithin(1000) { case x => x }
| }
res9: Any = 5
The problem here is that the calling code is not an actor, so the second case in your concurrentCalculator
actor does not match.
Try this, instead, and you should see what you expect:
val me = actor {
concurrentCalculator ! (Plus(2,3), self);
self.receiveWithin(1000) { case x => println(x) }
}
精彩评论