Developing Apama Applications > Developing Apama Applications in EPL > Testing and Tuning EPL > 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 {
   action onload() {
      on all Tick() {
         numTicks:=numTicks+1;
         emit NumberTicks(numTicks);
      }
      Calculate calc;
      on all Calculate():calc {
         integer atNumTicks:=numTicks;
         integer calcId:=integer.getUnique();
         spawn doCalculation(calc, calcId, context.current())
            to context(“Calculation”);
         CalculationResponse response;
         on CalculationResponse(calcId):resp {
            emit CalculationResult(resp, atNumTicks, numTicks);
         }
      }
   }
   action doCalculation(Calculate req, integer id, context caller) {
      float value:=actual_calculation_function(req);
      enqueue 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 enqueue a CalculationResponse event for 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 enqueued 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.
Copyright © 2013 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or Terracotta Inc., San Francisco, CA, USA, and/or Software AG (Canada) Inc., Cambridge, Ontario, Canada, and/or, Software AG (UK) Ltd., Derby, United Kingdom, and/or Software A.G. (Israel) Ltd., Or-Yehuda, Israel and/or their licensors.