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;
         send NumberTicks(numTicks) to "output";
      }
      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 {
            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.
Copyright © Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its Subsidiaries and or/its Affiliates and/or their licensors.
Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG.