In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.

A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.

The task

Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.

In order to test the object:

 set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
 wait 2s
 set the input to constant 0
 wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.

object ActiveObject {
 
  class Integrator {
 
    import java.util._
    import scala.actors.Actor._
 
    case class Pulse(t: Double)
    case class Input(k: Double => Double)
    case object Output
    case object Bye
 
    val timer = new Timer(true)
    var k: Double => Double = (_ => 0.0)
    var s: Double = 0.0
    var t0: Double = 0.0
 
    val handler = actor {
      loop {
        react {
          case Pulse(t1) => s += (k(t1) + k(t0)) * (t1 - t0) / 2.0; t0 = t1
          case Input(k) => this.k = k
          case Output => reply(s)
          case Bye => timer.cancel; exit
        }
      }
    }
 
    timer.scheduleAtFixedRate(new TimerTask {
      val start = System.currentTimeMillis
      def run { handler ! Pulse((System.currentTimeMillis - start) / 1000.0) }
    }, 0, 10) // send Pulse every 10 ms
 
    def input(k: Double => Double) = handler ! Input(k)
    def output = handler !? Output
    def bye = handler ! Bye
  }
 
  def main(args: Array[String]) {
    val integrator = new Integrator
    integrator.input(t => Math.sin(2.0 * Math.Pi * 0.5 * t))
    Thread.sleep(2000)
    integrator.input(_ => 0.0)
    Thread.sleep(500)
    println(integrator.output)
    integrator.bye
  }
}