Method call inside Actor freezes in Scala
I have the following code. If I comment out the call to "foo ()" inside the body of the actor, the code works fine. But if "foo ()" is activated ... my code hangs!
Does anyone know why?
import scala.actors.Actor._
object Main extends Application{
def foo() = {
println("I'm on foo")
}
def testActor() = {
val target = self
for(i <- 1 to 100){
actor{
foo()
target ! i
}
}
var total = 0
receive{
case x:Int => total += x
}
total
}
println("Result: " + testActor())
}
source to share
"testActor" is called when the "Main" class is initialized. The subject code is executing on a different thread (not the main thread) and it is blocked and cannot send any message because it is trying to access a method on a class (in this case Main) that is initialized on the main thread. "receive" hangs because it cannot receive any message.
Don't use "extends Application". Use "def main (args: Array [String])" and save yourself a ton of trouble.
See http://scala-blogs.org/2008/07/application-trait-considered-harmful.html
source to share
Sign Application
and its use here. When you have code that runs inside the body Application
and not inside a method main
, that code is actually executed as part of the constructor. Therefore, at the point where you call the testActor () method, the object has not actually completed initialization.
To fix this, move the println line into the main method:
def main (args: Array[String]) {
println("Result: " + testActor())
}
Because this problem happens so easily, Application
bad news is considered a sign .
source to share