This class represents all the logic necessary for split and aggregate grid enabling of credit risk calculation. There are two methods in this class responsible for splitting method invocation into multiple sub-calls and aggregating results back from splits.
Full Source Code
CreditRiskGridTask.java
package org.gridgain.examples.montecarlo.gigaspaces; import com.j_spaces.core.client.*; import java.io.*; import java.util.*; import org.gridgain.grid.*; import org.gridgain.grid.gridify.*; public class CreditRiskGridTask extends GridTaskSplitAdapter<GridifyArgument> { /** */ private static final long serialVersionUID = 65998740421155825L; /** * {@inheritDoc} */ @Override protected Collection<? extends GridJob> split(int gridSize, final GridifyArgument arg) { // Split number of iterations. Integer iterations = ((Integer)arg.getMethodParameters()[2]); // Number of iterations should be done by each node. int iterPerNode = Math.round(iterations / (float)gridSize); // Number of iterations for the last/the only node. int lastNodeIter = iterations - (gridSize - 1) * iterPerNode; List<GridJobAdapter<Integer>> jobs = new ArrayList<GridJobAdapter<Integer>>(gridSize); // Note that for the purpose of this example we perform a simple homogeneous // (non weighted) split assuming that all computing resources in this split // will be identical. In real life scenarios when heterogeneous environment // is used a split that is weighted by, for example, CPU benchmarks of each // node in the split will be more efficient. It is fairly easy addition and // GridGain comes with convenient Spring-compatible benchmark that can be // used for weighted splits. for (int i = 0; i < gridSize; i++) { // Add new job reference to the split. jobs.add(new GridJobAdapter<Integer>(i == gridSize - 1 ? lastNodeIter : iterPerNode) { /** */ private static final long serialVersionUID = 7675691702376008368L; /** * {@inheritDoc} */ public Serializable execute() throws GridException { Object[] params = arg.getMethodParameters(); try { return new CreditRiskManager().calculateCreditRiskMonteCarlo((String)params[0], (String)params[1], getArgument(), (Integer)params[3], (Double)params[4]); } catch (FinderException e) { throw new GridException("Failed to calculate Monte Carlo simulation: " + this, e); } } }); } // Trigger remote execution with given job references. return jobs; } /** * {@inheritDoc} */ public Serializable reduce(List<GridJobResult> results) throws GridException { double taskRes = 0; // Reduce results by summing them. for (GridJobResult res : results) { if (res.getException() != null) { throw res.getException(); } // Note that since we use Gridify annotation for grid enabling // we know what type of result data to expect. taskRes += (Double)res.getData(); } return taskRes / results.size(); } }
