Apama 10.11.3 | Developing Apama Applications | Developing Apama Applications in EPL | Defining Monitors | Spawning monitor instances | Terminating monitor instances
 
Terminating monitor instances
The example discussed in Sample code for spawning spawns a monitor instance for each newStock event that the initial monitor instance receives. This is not always desirable. For example, if two identical newStock events are received, two identical monitor instances are spawned. To prevent this, you can use the die statement to delete a monitor instance if a more recent one (with the same spawning properties) has been created. For example:
action onload() {
   on all NewStock(*, *):chosenStock spawn matchTicks();
}
action matchTicks() {
   on NewStock (chosenStock.name, chosenStock.owner) die;
   // ...
}
In this fragment, the monitor spawns when it receives a NewStock event. In the spawned monitor instance, the initial on statement activates an event listener for a NewStock event that is identical to the one that caused the spawning. In other words, the spawned monitor instance is listening for a NewStock event where the fields are the same as that held by the chosenStock variable. If such an event arrives, the monitor instance terminates. This structure ensures that only one monitor instance for each stock name and owner exists at any one time. The same NewStock event kills the existing monitor instance and causes spawning of a new monitor instance. That is, the same event triggers the concurrent event listeners of the initial monitor and the spawned monitor instance.
In this solution, when a NewStock event kills an existing monitor instance and spawns a new monitor instance, the value of the numberTicks variable in the new instance is zero. Often, this kind of behavior is required. You want to ignore the state of the old monitor instance and start afresh.
Note that the event that triggers the initial monitor instance's event listener and causes the spawning of a monitor instance does not get processed by the spawned monitor instance's new event listener. An event is available to only those event listeners that are active when the correlator receives the event.
You can also use the die statement to kill a monitor instance at will. For example, consider the following fragments:
event StopStock {
   string name;
   string owner;
}
 
action onload() {
   on all newStock(*, *):chosenStock spawn matchTicks();
}
 
action matchTicks() {
   on StopStock (chosenStock.name, chosenStock.owner) die;
   // . . .
}
Traders would send StopStock events when they are no longer interested in a particular stock. Receiving a matching StopStock event kills the monitor instance that is listening for that stock. You can use this technique to explicitly kill any monitor instance.