summaryrefslogtreecommitdiff
path: root/src/actors/scala/actors/ReactorTask.scala
blob: 1ca061b40dbaf0cda06ae2d9bbd931b422c85252 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2005-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */


package scala.actors

import java.lang.Runnable
import java.util.concurrent.Callable

import scala.concurrent.forkjoin.RecursiveAction

/**
 *  @author Philipp Haller
 */
private[actors] class ReactorTask[Msg >: Null](var reactor: Reactor[Msg],
                                               var fun: () => Any,
                                               var handler: PartialFunction[Msg, Any],
                                               var msg: Msg)
  extends RecursiveAction with Callable[Unit] with Runnable {

  def run() {
    try {
      beginExecution()
      try {
        if (fun eq null)
          handler(msg)
        else
          fun()
      } catch {
        case _: KillActorControl =>
          // do nothing

        case e: Exception if reactor.exceptionHandler.isDefinedAt(e) =>
          reactor.exceptionHandler(e)
      }
      reactor.kill()
    }
    catch {
      case _: SuspendActorControl =>
        // do nothing (continuation is already saved)

      case e: Throwable =>
        terminateExecution(e)
        reactor.terminated()
        if (!e.isInstanceOf[Exception])
          throw e
    } finally {
      suspendExecution()
      this.reactor = null
      this.fun = null
      this.handler = null
      this.msg = null
    }
  }

  def call() = run()

  def compute() = run()

  protected def beginExecution() {}

  protected def suspendExecution() {}

  protected def terminateExecution(e: Throwable) {
    Console.err.println(reactor+": caught "+e)
    e.printStackTrace()
  }

}