Actorã§ã®ä¾å¤å¦ç
Scala ã® Actor ã¯ãã¡ãã»ã¼ã¸å¦çä¸ã«ä¾å¤ãçºçãã㨠Actor èªä½ãçµäºããããã«ãªã£ã¦ãã¾ãã
ä¾å¤ãå¦çãããå ´åã«ãä»ã¾ã§ã¯ case ã try ã catch ã§å²ãã§ããã®ã§ããã©ãããã¾ãã¡ãªæãã§ããã以ä¸ã¯ try ã catch ã§å²ãã§ããä¾ã§ãã
actor { loop { react { case 'foo => try { ... } catch { ... } case 'bar => try { ... } catch { ... } } } }
ãã°ããã¯å¿ãã¦ããã®ã§ããããµã¨ããã¨ãã« link ã使ã£ã¦ä¾å¤ãå¦çãã Actor ãä½ãã°ãããã¨ã«æ°ä»ãã¾ããã
ä¸è¨ã®ä¾ã§ã¯ã1 ç§å¾ã«æ£å¸¸çµäºã2 ç§å¾ã«ä¾å¤çºçã3 ç§å¾ã«ããã°ã©ã ãçµäºãã(ããªã¬ã«ãªã) Actor ãèµ·åãã¾ãã
import scala.actors._ import Actor._ object HandleException { def main(arguments: Array[String]): Unit = { val workers = actor { self.trapExit = true loop { react { case work: Work => val worker = new Worker(work) link(worker) worker.start case Exit(worker:Worker, reason:Throwable) => printf("[Failure]The worker(%s) died.(reason=%s)\n", worker.name, reason) case Exit(worker:Worker, reason) => printf("[Success]The worker(%s) completed.(reason=%s)\n", worker.name, reason) case 'exit => exit }} } workers ! new Work("foo", 1000, {println("[Work]foo work.")}) workers ! new Work("bar", 2000, {throw new Exception("bar fail.")}) workers ! new Work("baz", 3000, {workers ! 'exit}) } } class Work(val name: String, val delay: Int, f: => Unit) { def apply(): Unit = f } class Worker(work: Work) extends Actor { val name = work.name def act = reactWithin(work.delay) { case TIMEOUT => work() } }
å®è¡çµæã¯ä»¥ä¸ã®ã¨ããã
[Work]foo work.
[Success]The worker(foo) completed.(reason='normal)
[Failure]The worker(bar) died.(reason=java.lang.Exception: bar fail.)
link ã使ããã¨ã§ãlink å
ã® Actor ãçµäºããã¨ãã« Exit ã¡ãã»ã¼ã¸ãéããã¦ãã¾ããããã¯ä¾å¤ã«ãã£ã¦çµäºãã¦ãã¾ã£ãå ´åã§ãåæ§ã§ãã
ä¾å¤ã«ãã£ã¦çµäºããå ´åãExit ã® reason ã«ä¾å¤ã®ã¤ã³ã¹ã¿ã³ã¹ãè¨å®ããã¦ãã¾ããä¸è¨ä¾ã§ã¯ãreason ã®åã Throwable ã®å ´åã¨ããã§ãªãå ´åã¨ã§ case ãåãããã¨ã§ãæ£å¸¸çµäºã¨ç°å¸¸çµäºãåãåãã¦ãã¾ãã
ãã¹ã¦ã¯ Actor ã¨ããã®ãã¡ãã£ã¨å®æãã¾ãããä¾å¤ãå¦çããããªããä¾å¤ãå¦çãã Actor ãéã«æãã£ã¦ãã¨ã§ããã»ã»ã»