GridGain™ 2.1.0
Java API Specification

org.gridgain.grid.spi.loadbalancing.weightedrandom
Class GridWeightedRandomLoadBalancingSpi

java.lang.Object
  extended by org.gridgain.grid.spi.GridSpiAdapter
      extended by org.gridgain.grid.spi.loadbalancing.weightedrandom.GridWeightedRandomLoadBalancingSpi
All Implemented Interfaces:
GridSpi, GridSpiManagementMBean, GridLoadBalancingSpi, GridWeightedRandomLoadBalancingSpiMBean

@GridSpiInfo(author="GridGain Systems",
             url="www.gridgain.org",
             email="support@gridgain.com",
             version="x.x")
@GridSpiMultipleInstancesSupport(value=true)
public class GridWeightedRandomLoadBalancingSpi
extends GridSpiAdapter
implements GridLoadBalancingSpi, GridWeightedRandomLoadBalancingSpiMBean

Load balancing SPI that picks a random node for job execution. Note that you can optionally assign weights to nodes, so nodes with larger weights will end up getting proportionally more jobs routed to them (see GridWeightedRandomLoadBalancingSpi.setNodeWeight(int) configuration property). By default all nodes get equal weight defined by GridWeightedRandomLoadBalancingSpi.DFLT_NODE_WEIGHT (value is 10).

Coding Example

If you are using GridTaskSplitAdapter then load balancing logic is transparent to your code and is handled automatically by the adapter. Here is an example of how your task could look:
 public class MyFooBarTask extends GridTaskSplitAdapter<Object, Object> {
    @Override
    protected Collection<? extends GridJob> split(int gridSize, Object arg) throws GridException {
        List<MyFooBarJob> jobs = new ArrayList<MyFooBarJob>(gridSize);

        for (int i = 0; i < gridSize; i++) {
            jobs.add(new MyFooBarJob(arg));
        }

        // Node assignment via load balancer
        // happens automatically.
        return jobs;
    }
    ...
 }
 
If you need more fine-grained control over how some jobs within task get mapped to a node and use affinity load balancing for some other jobs within task, then you should use GridTaskAdapter. Here is an example of how your task will look. Note that in this case we manually inject load balancer and use it to pick the best node. Doing it in such way would allow user to map some jobs manually and for others use load balancer.
 public class MyFooBarTask extends GridTaskAdapter<String, String> {
    // Inject load balancer.
    @GridLoadBalancerResource
    GridLoadBalancer balancer;

    // Map jobs to grid nodes.
    public Map<? extends GridJob, GridNode> map(List<GridNode> subgrid, String arg) throws GridException {
        Map<MyFooBarJob, GridNode> jobs = new HashMap<MyFooBarJob, GridNode>(subgrid.size());

        // In more complex cases, you can actually do
        // more complicated assignments of jobs to nodes.
        for (int i = 0; i < subgrid.size(); i++) {
            // Pick the next best balanced node for the job.
            jobs.put(new MyFooBarJob(arg), balancer.getBalancedNode())
        }

        return jobs;
    }

    // Aggregate results into one compound result.
    public String reduce(List<GridJobResult> results) throws GridException {
        // For the purpose of this example we simply
        // concatenate string representation of every
        // job result
        StringBuilder buf = new StringBuilder();

        for (GridJobResult res : results) {
            // Append string representation of result
            // returned by every job.
            buf.append(res.getData().toString());
        }

        return buf.toString();
    }
 }
 

Configuration

In order to use this load balancer, you should configure your grid instance to use GridRandomLoadBalancingSpi either from Spring XML file or directly. The following configuration parameters are supported:

Mandatory

This SPI has no mandatory configuration parameters.

Optional

The following configuration parameters are optional: Below is Java configuration example:
 GridWeightedRandomLoadBalancingSpi = new GridWeightedLoadBalancingSpi();

 // Configure SPI to used weighted
 // random load balancing.
 spi.setUseWeights(true);

 // Set weight for the local node.
 spi.setWeight( *);

 GridConfigurationAdapter cfg = new GridConfigurationAdapter();

 // Override default load balancing SPI.
 cfg.setLoadBalancingSpi(spi);

 // Start grid.
 GridFactory.start(cfg);
 
Here is how you can configure GridRandomLoadBalancingSpi using Spring XML configuration:
 <property name="loadBalancingSpi">
     <bean class="org.gridgain.grid.spi.loadbalancing.weightedrandom.GridWeightedRandomLoadBalancingSpi">
         <property name="useWeights" value="true"/>
         <property name="nodeWeight" value="10"/>
     </bean>
 </property>
 


For information about Spring framework visit www.springframework.org



See Also:

  Documentation
  Email Support
  Online Forums
  Issue Tracking

Author:   2005-2008 Copyright © GridGain Systems. All Rights Reserved. ver. 2.1.0

 

Field Summary
static int DFLT_NODE_WEIGHT
          Default weight assigned to every node if explicit one is not provided (value is 10).
static String NODE_WEIGHT_ATTR_NAME
          Name of node attribute used to indicate load weight of a node (value is "gridgain.node.weight.attr.name").
 
Constructor Summary
GridWeightedRandomLoadBalancingSpi()
           
 
Method Summary
 GridNode getBalancedNode(GridTaskSession ses, List<GridNode> top, GridJob job)
          Gets balanced node for specified job within given task session.
protected  List<String> getConsistentAttributeNames()
          Returns back list of attributes that should be consistent for this SPI.
 Map<String,Serializable> getNodeAttributes()
          This method is called before SPI starts (before method GridSpi.spiStart(String) is called). It allows SPI implementation to add attributes to a local node. Kernel collects these attributes from all SPI implementations loaded up and then passes it to discovery SPI so that they can be exchanged with other nodes.
 int getNodeWeight()
          Gets weight of this node.
 boolean isUseWeights()
          Checks whether node weights are considered when doing random load balancing.
 void onContextDestroyed()
          Callback invoked prior to stopping grid before SPI context is destroyed. Once this method is complete, grid will begin shutdown sequence. Use this callback for de-initialization logic that may involve SPI context. Note that invoking SPI context after this callback is complete is considered illegal and may produce unknown results.

If GridSpiAdapter is used for SPI implementation, then it will replace actual context with dummy no-op context which is usually good-enough since grid is about to shut down.

 void onContextInitialized(GridSpiContext spiCtx)
          Callback invoked when SPI context is initialized. SPI implementation may store SPI context for future access.

This method is invoked after GridSpi.spiStart(String) method is completed, so SPI should be fully functional at this point. Use this method for post-start initialization, such as subscribing a discovery listener, sending a message to remote node, etc...

 void setNodeWeight(int nodeWeight)
          Sets weight of this node.
 void setUseWeights(boolean isUseWeights)
          Sets a flag to indicate whether node weights should be checked when doing random load balancing.
 void spiStart(String gridName)
          This method is called to start SPI.
 void spiStop()
          This method is called to stop SPI.
 String toString()
          
 
Methods inherited from class org.gridgain.grid.spi.GridSpiAdapter
assertParameter, configInfo, createSpiAttributeName, getAuthor, getGridGainHome, getLocalNodeId, getName, getSpiContext, getStartTimestamp, getStartTimestampFormatted, getUpTime, getUpTimeFormatted, getVendorEmail, getVendorUrl, getVersion, registerMBean, setName, setSpiContext, startInfo, startStopwatch, stopInfo, unregisterMBean
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.gridgain.grid.spi.GridSpi
getName
 
Methods inherited from interface org.gridgain.grid.spi.GridSpiManagementMBean
getAuthor, getGridGainHome, getLocalNodeId, getName, getStartTimestamp, getStartTimestampFormatted, getUpTime, getUpTimeFormatted, getVendorEmail, getVendorUrl, getVersion
 

Field Detail

NODE_WEIGHT_ATTR_NAME

public static final String NODE_WEIGHT_ATTR_NAME
Name of node attribute used to indicate load weight of a node (value is "gridgain.node.weight.attr.name").

See Also:
GridNode.getAttributes(), Constant Field Values

DFLT_NODE_WEIGHT

public static final int DFLT_NODE_WEIGHT
Default weight assigned to every node if explicit one is not provided (value is 10).

See Also:
Constant Field Values
Constructor Detail

GridWeightedRandomLoadBalancingSpi

public GridWeightedRandomLoadBalancingSpi()
Method Detail

setUseWeights

@GridSpiConfiguration(optional=true)
public void setUseWeights(boolean isUseWeights)
Sets a flag to indicate whether node weights should be checked when doing random load balancing. Default value is false which means that node weights are disregarded for load balancing logic.

Parameters:
isUseWeights - If true then random load is distributed according to node weights.

isUseWeights

public boolean isUseWeights()
Checks whether node weights are considered when doing random load balancing.

Specified by:
isUseWeights in interface GridWeightedRandomLoadBalancingSpiMBean
Returns:
If true then random load is distributed according to node weights.

setNodeWeight

@GridSpiConfiguration(optional=true)
public void setNodeWeight(int nodeWeight)
Sets weight of this node. Nodes with more processing capacity should be assigned proportionally larger weight. Default value is GridWeightedRandomLoadBalancingSpi.DFLT_NODE_WEIGHT and is equal for all nodes.

Parameters:
nodeWeight - Weight of this node.

getNodeWeight

public int getNodeWeight()
Gets weight of this node.

Specified by:
getNodeWeight in interface GridWeightedRandomLoadBalancingSpiMBean
Returns:
Weight of this node.

getNodeAttributes

public Map<String,Serializable> getNodeAttributes()
                                           throws GridSpiException
This method is called before SPI starts (before method GridSpi.spiStart(String) is called). It allows SPI implementation to add attributes to a local node. Kernel collects these attributes from all SPI implementations loaded up and then passes it to discovery SPI so that they can be exchanged with other nodes.

Specified by:
getNodeAttributes in interface GridSpi
Overrides:
getNodeAttributes in class GridSpiAdapter
Throws:
GridSpiException - Throws in case of any error.
Returns:
Map of local node attributes this SPI wants to add.

spiStart

public void spiStart(@Nullable
                     String gridName)
              throws GridSpiException
This method is called to start SPI. After this method returns successfully kernel assumes that SPI is fully operational.

Specified by:
spiStart in interface GridSpi
Throws:
GridSpiException - Throws in case of any error during SPI start.
Parameters:
gridName - Name of grid instance this SPI is being started for (null for default grid).

spiStop

public void spiStop()
             throws GridSpiException
This method is called to stop SPI. After this method returns kernel assumes that this SPI is finished and all resources acquired by it are released. Note that this method can be called at any point including during recovery of failed start. It should make no assumptions on what state SPI will be in when this method is called.

Specified by:
spiStop in interface GridSpi
Throws:
GridSpiException - Thrown in case of any error during SPI stop.

onContextInitialized

public void onContextInitialized(GridSpiContext spiCtx)
                          throws GridSpiException
Callback invoked when SPI context is initialized. SPI implementation may store SPI context for future access.

This method is invoked after GridSpi.spiStart(String) method is completed, so SPI should be fully functional at this point. Use this method for post-start initialization, such as subscribing a discovery listener, sending a message to remote node, etc...

Specified by:
onContextInitialized in interface GridSpi
Overrides:
onContextInitialized in class GridSpiAdapter
Throws:
GridSpiException - If context initialization failed (grid will be stopped).
Parameters:
spiCtx - Spi context.

onContextDestroyed

public void onContextDestroyed()
Callback invoked prior to stopping grid before SPI context is destroyed. Once this method is complete, grid will begin shutdown sequence. Use this callback for de-initialization logic that may involve SPI context. Note that invoking SPI context after this callback is complete is considered illegal and may produce unknown results.

If GridSpiAdapter is used for SPI implementation, then it will replace actual context with dummy no-op context which is usually good-enough since grid is about to shut down.

Specified by:
onContextDestroyed in interface GridSpi
Overrides:
onContextDestroyed in class GridSpiAdapter

getBalancedNode

public GridNode getBalancedNode(GridTaskSession ses,
                                List<GridNode> top,
                                GridJob job)
Gets balanced node for specified job within given task session.

Specified by:
getBalancedNode in interface GridLoadBalancingSpi
Parameters:
ses - Grid task session for currently executing task.
top - Topology of task nodes from which to pick the best balanced node for given job.
job - Job for which to pick the best balanced node.
Returns:
Best balanced node for the given job within given task session.

getConsistentAttributeNames

protected List<String> getConsistentAttributeNames()
Returns back list of attributes that should be consistent for this SPI. Consistency means that remote node has to have the same attribute with the same value.

Overrides:
getConsistentAttributeNames in class GridSpiAdapter
Returns:
List or attribute names.

toString

public String toString()

Overrides:
toString in class Object

GridGain™ 2.1.0
Java API Specification

GridGain™ - Grid Computing Made Simple, ver. 2.1.0.19122008
2005-2008 Copyright © GridGain Systems. All Rights Reserved.