Apama 10.7.2 | Developing Apama Applications | Developing Apama Applications in EPL | Testing and Tuning EPL monitors | Tuning contexts | Parallel processing for long-running calculations
 
Parallel processing for long-running calculations
Suppose a required calculation takes a relatively long time. You can do the calculation in a context while the main context performs other operations. Or, you might want multiple contexts to concurrently perform the long calculation on different groups of the incoming events.
The following code provides an example of performing the calculation in another context.
monitor parallel {
integer numTicks;
   action onload() {
      on all Tick() {
         numTicks:=numTicks+1;
         send NumberTicks(numTicks) to "output";
      }
      on all Calculate() as calc {
         integer atNumTicks:=numTicks;
         integer calcId:=integer.getUnique();
         spawn doCalculation(calc, calcId, context.current())
            to context("Calculation");
         on CalculationResponse(id=calcId) as resp {
            send CalculationResult(resp, atNumTicks, numTicks) to "output";
         }
      }
   }
   action doCalculation(Calculate req, integer id, context caller) {
      float value:=actual_calculation_function(req);
      send CalculationResponse(id, value) to caller;
   }
}
For each Calculate event found, the event listener specifies a spawn...to statement that creates a new context. All contexts have the same name — Calculation — and a different context ID. All contexts can run concurrently.
A Calculation context might send a CalculationResponse event to the main context before the main context sets up the CalculationResponse event listener. However, the correlator completes the operations, including setting up the CalculationResponse event listener, that result from finding a Calculate event before it processes the sent CalculationResponse event.
While the calculations are running, other Tick events might arrive from external components and the correlator can process them.
The order in which CalculationResponse events arrive on the main context's input queue can be different from the order of creation of the contexts that generated the CalculationResponse events. The order of responses depends on when the calculation started and how long it took to complete the calculation. The monitor instance in the main context uses the calcId variable to distinguish responses.