Dashboard > GridGain User Guide > Table Of Contents > Examples Gallery > Groovy HelloWorld - Basic Grid Task
Groovy HelloWorld - Basic Grid Task
Added by link, last edited by link on Feb 02, 2009  (view change)
Labels: 
(None)


Groovy Basic Grid Task Example

Package:
org.gridgain.grid.groovy.examples.helloworld.api

This example contains Groovy HelloWorld example that is using direct grid task execution. It demonstrates a simple use of GridGain grid. String "Hello World" is passed as an argument for execution of GridHelloWorldTask task. The task will split the passed in string into separate words and execute each word on a different node. As an outcome, one node will print out word "Hello" and the other will printout word "World". If there is only one node participating, then it will print out both words.

There are three classes implemented for this example:

Running Grid Node

This example will need one remote node to be running. Note that you don't need another machine for it - you can start remote node on the same machine you are running example on.

To start a remote node open the terminal window on Linux/Mac OS X or Command Prompt on Windows, change directory to ${GRIDGAIN_HOME}/bin and run the gridgain.{sh|bat} script. It takes 2-3 seconds for grid node to start and if everything worked fine you should see starting log ending with successful start acknowledgment.

Compile and Run Example

Groovy version

All groovy examples scripts used for groovy-1.5.7 version.
Change all scripts in ${GRIDGAIN_HOME}/examples/groovy folder according your own groovy installation.

Incorrect gridgain.jar name in groovy examples scripts in 2.1.0 release

Groovy Gridgain 2.1.0 release contains incorrect jar name in compile*.{sh|bat} scripts.
Please change name gridgain.jar to gridgain-2.1.0.jar or create symbolic link in ${GRIDGAIN_HOME}
'ln -s gridgain-2.1.0.jar gridgain.jar'

Make sure that Groovy environment configured properly.
Run script compileHelloWorld.{sh|bat} to compile example groovy files.
Use script runHelloWorld.{sh|bat} to run example.

GridHelloWorldGroovyExample.groovy

1. Import GridGain classes.

import org.gridgain.grid.*;

2. Add Grid Start and Stop.

GridFactory.start();
        
try {
    ...
}
finally {
    GridFactory.stop(true);
}

finally clause allows for graceful grid shutdown in case of the exceptions.

3. Add Grid Task Execution.

GridTaskFuture<Object> future = grid.execute(GridHelloWorldGroovyTask.class, "Hello World");

// Wait for the task to complete.
fugure.get();

Note that method grid.execute(...) returns GridTaskFuture Javadoc . Method get() on GridTaskFuture Javadoc allows to block until task execution is completed. This is a standard approach borrowed from java.util.concurrent.Future interface.

Source Code (edited)

GridHelloWorldGroovyExample.groovy
package org.gridgain.grid.groovy.examples.helloworld.api;

import org.gridgain.grid.*;

class GridHelloWorldGroovyExample {
    static void main(args) {
        if (args.size() == 0) {
            GridFactory.start();
        }
        else {
            GridFactory.start(args[0]);
        }

        try {
            Grid grid = GridFactory.getGrid();

            // Execute Hello World task.
            GridTaskFuture<Integer> future = grid.execute(GridHelloWorldGroovyTask.class, "Hello World");

            // Wait for task completion.
            def phraseLen = future.get();

            println ">>>"
            println ">>> Finished executing Grid \"Hello World\" example with custom task."
            println ">>> Total number of characters in the phrase is '$phraseLen'."
            println ">>> You should see print out of 'Hello' on one node and 'World' on another node."
            println ">>> Check all nodes for output (this node is also part of the grid)."
            println ">>>"
        }
        finally {
            GridFactory.stop(true);
        }
    }
}

GridHelloWorldGroovyTask.groovy

This is a grid task implementation that is responsible for split and aggregate (a.k.a map/reduce) logic. Note that this implementation uses GridTaskSplitAdapter Javadoc that simplifies API for grid tasks in homogeneous grids (which is often the case). Main two methods that are implemented here are split and reduce. Method reduce aggregates result (number of characters in the string) returned from every node.

Source Code (edited)

GridHelloWorldGroovyTask.java
package org.gridgain.grid.groovy.examples.helloworld.api;

import org.gridgain.grid.*

class GridHelloWorldGroovyTask extends GridTaskSplitAdapter<String, Integer> {
    public Collection split(int gridSize, Object phrase) throws GridException {
        // Split the passed in phrase into multiple words separated by spaces.
        String[] words = ((String)phrase).split(" ");

        List<GridJob> jobs = new ArrayList<GridJob>(words.length);

        for (String word : words) {
            // Every job gets its own word as an argument.
            jobs.add(new GridHelloWorldGroovyJob(word));
        }


        return jobs;
    }

    public Object reduce(List results) throws GridException {
        int totalCharCnt = 0;

        for (GridJobResult res : ((List<GridJobResult>)results)) {
            // Every job returned a number of letters
            // for the word it was responsible for.
            Integer charCnt = res.getData();

            totalCharCnt += charCnt;
        }

        // Account for spaces. For simplicity we assume one space between words.
        totalCharCnt += results.size() - 1;

        // Total number of characters in the phrase
        // passed into task execution.
        return (Integer)totalCharCnt;
    }
}

GridHelloWorldGroovyJob.groovy

This is a grid job implementation.

Source Code (edited)

GridHelloWorldGroovyJob.groovy
package org.gridgain.grid.groovy.examples.helloworld.api;

import org.gridgain.grid.*;
import org.gridgain.grid.logger.*;
import org.gridgain.grid.resources.*;

class GridHelloWorldGroovyJob extends GridJobAdapter<String> {
    /** Grid logger. */
    @GridLoggerResource
    def GridLogger log = null

    /**
     * Constructor.
     */
    public GridHelloWorldGroovyJob(String word) {
        super()

        super.setArgument(word)
    }

    /**
     * {@inheritDoc}
     */
    public Serializable execute() {
        def arg = getArgument()

        if (log.isInfoEnabled() == true) {
            log.info(">>>");
            log.info(">>> Printing '" + arg + "' on this node from grid job.");
            log.info(">>>");
        }

        return arg.size()
    }
}

Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.2.10 Build:#528 Nov 29, 2006) - Bug/feature request - Contact Administrators