Skip to content
laforge49 edited this page Jul 13, 2011 · 10 revisions

Programs must often deal with lifecycle issues, where the order in which services are created, opened and closed is critical. Actors are careful about the order in which their components are created. This is done by creating components after creating the components they depend on. The System Services actor provides additional lifecycle support.

When the open function on the System Services actor is called, it calls the open function of each of its components in the same order that the components were created. Similarly, when the close function on the System Services actor is called, it calls the close function in reverse order.

We can illustrate this with two simple components which print a message when they are opened or closed.

class SC1Factory extends ComponentFactory {
  addDependency(classOf[SC2Factory])
  override protected def instantiate(actor: Actor) = new SC1(actor, this)
}

class SC1(actor: Actor, componentFactory: ComponentFactory) extends Component(actor, componentFactory) {
  override def open {println("SC1 open")}
  override def close {println("SC1 close")}
}

class SC2Factory extends ComponentFactory {
  override protected def instantiate(actor: Actor) = new SC2(actor, this)
}

class SC2(actor: Actor, componentFactory: ComponentFactory) extends Component(actor, componentFactory) {
  override def open {println("SC2 open")}
  override def close {println("SC2 close")}
}

Since SC1 depends on SC2, SC2 should be opened before SC1 and SC1 should be closed before SC2. The test code for this is quite brief.

val systemServices = SystemServices(new SC1Factory)
systemServices.open
systemServices.close

And here is the output.

SC2 open SC1 open SC1 close SC2 close

Clone this wiki locally