Пример #1
0
  /**
   * Calculates length of a given phrase on the grid.
   *
   * @param phrase Phrase to count the number of letters in.
   * @throws GridException If failed.
   */
  private static void countLettersReducer(String phrase) throws GridException {
    X.println(">>> Starting countLettersReducer() example...");

    Grid grid = G.grid();

    // Logger to use in your closure. Note that even though we assign it
    // to a local variable, GridGain still allows to use it from remotely
    // executed code.
    final GridLogger log = grid.log();

    // Execute Hello World task.
    int letterCnt =
        grid.reduce(
            BALANCE,
            new GridClosure<String, Integer>() { // Create executable logic.
              @Override
              public Integer apply(String word) {
                // Print out a given word, just so we can
                // see which node is doing what.
                log.info(">>> Calculating for word: " + word);

                // Return the length of a given word, i.e. number of letters.
                return word.length();
              }
            },
            Arrays.asList(phrase.split(" ")), // Collection of words.
            // Create custom reducer.
            // NOTE: Alternatively, you can use existing reducer: F.sumIntReducer()
            new GridReducer<Integer, Integer>() {
              private int sum;

              @Override
              public boolean collect(Integer res) {
                sum += res;

                return true; // True means continue collecting until last result.
              }

              @Override
              public Integer apply() {
                return sum;
              }
            });

    X.println(">>>");
    X.println(">>> Finished execution of counting letters with reducer based on GridGain 3.0 API.");
    X.println(">>> Total number of letters in the phrase is '" + letterCnt + "'.");
    X.println(">>> You should see individual words printed out on different nodes.");
    X.println(">>> Check all nodes for output (this node is also part of the grid).");
    X.println(">>>");
  }
  /**
   * @param args Command arguments.
   * @throws GridException If failed.
   */
  public static void main(String[] args) throws GridException {
    // Starts grid.
    Grid grid = args.length == 0 ? G.start() : G.start(args[0]);

    try {
      // Create portfolio.
      GridCredit[] portfolio = new GridCredit[5000];

      Random rnd = new Random();

      // Generate some test portfolio items.
      for (int i = 0; i < portfolio.length; i++) {
        portfolio[i] =
            new GridCredit(
                50000 * rnd.nextDouble(), // Credit amount.
                rnd.nextInt(1000), // Credit term in days.
                rnd.nextDouble() / 10, // APR.
                rnd.nextDouble() / 20 + 0.02 // EDF.
                );
      }

      // Forecast horizon in days.
      int horizon = 365;

      // Number of Monte-Carlo iterations.
      int iter = 10000;

      // Percentile.
      double percentile = 0.95;

      // Mark the stopwatch.
      long start = System.currentTimeMillis();

      // Calculate credit risk and print it out.
      // As you can see the grid enabling is completely hidden from the caller
      // and it is fully transparent to him. In fact, the caller is never directly
      // aware if method was executed just locally or on the 100s of grid nodes.
      // Credit risk crdRisk is the minimal amount that creditor has to have
      // available to cover possible defaults.
      double crdRisk =
          grid.reduce(
              SPREAD,
              closures(grid.size(), portfolio, horizon, iter, percentile),
              new R1<Double, Double>() {
                /** Collected values sum. */
                private double sum;

                /** Collected values count. */
                private int count;

                /** {@inheritDoc} */
                @Override
                public boolean collect(Double e) {
                  sum += e;
                  count++;

                  return true;
                }

                /** {@inheritDoc} */
                @Override
                public Double apply() {
                  return sum / count;
                }
              });

      X.println(
          "Credit risk [crdRisk="
              + crdRisk
              + ", duration="
              + (System.currentTimeMillis() - start)
              + "ms]");
    }
    // We specifically don't do any error handling here to
    // simplify the example. Real application may want to
    // add error handling and application specific recovery.
    finally {
      // Stops grid.
      G.stop(true);
    }
  }