Scala actor blocking the current thread

I tried to implement a timer based on the Scala act API, with the current Thread actor (Actor.self) as a timer and an anonymous actor who is doing work that needs to be completed on time. I have the following Scala program

import scala.actors.Actor.self import scala.actors.TIMEOUT object Main { def main(args: Array[String]): Unit = { val thiz = self actor { // do heavy work here thiz ! "finish" } self.reactWithin(1000) { case "finish" => println("complete") case TIMEOUT => println("timeout") } } } 

When I run the program, I got

 Exception in thread "main" scala.actors.SuspendActorControl scala.actors.ActorProxy@1d99a4d : caught java.lang.InterruptedException 

Please show me a way to overcome the problem.

+4
source share
1 answer

You have two types of control going on with scala actors, thread blocking, or thread suspension . the latter means that a control exception is thrown (the thread again becomes available to the thread pool manager), and the actor’s body is re-executed when the message enters his inbox. See the tutorial for actors for more information. section "Make a thread less!".

The receiveWithin method uses thread blocking and reactWithin suspension. The problem you have here is that there is no external manager who catches the exception. This only works in the "right" actor, and not with a proxy server created for the main thread. Therefore, if you want to wait for the main thread outside the explicit actor, you need to use / receiveWithin thread receiveWithin :

 self.receiveWithin(1000) { ... } 
+6
source

All Articles