Micro cloud in your JVM: code example…

Few days ago I blogged about how GridGain easily supports starting many GridGain nodes in the single JVM - which is a huge productivity boost during the development. I've got a lot of requests to show the code - so here it is. This is an example that we are shipping with upcoming 4.3 release (entire source code):

[source lang="java" title="Micro cloud example"]
import org.gridgain.grid.*;
import org.gridgain.grid.spi.discovery.tcp.*;
import org.gridgain.grid.spi.discovery.tcp.ipfinder.*;
import org.gridgain.grid.spi.discovery.tcp.ipfinder.vm.*;
import org.gridgain.grid.typedef.*;

import javax.swing.*;
import java.util.concurrent.*;

public class GridJvmCloudExample {
/** Number of nodes to start. */
private static final int NODE_COUNT = 5;

/**
* Starts multiple nodes in the same JVM.
*/
public static void main(String[] args) throws Exception {
try {
ExecutorService exe = new ThreadPoolExecutor(
NODE_COUNT,
NODE_COUNT,
0,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()
);

// Shared IP finder for in-VM node discovery.
final GridTcpDiscoveryIpFinder ipFinder =
new GridTcpDiscoveryVmIpFinder(true);

for (int i = 0; i < NODE_COUNT; i++) {
final String nodeName = "jvm-node-" + i;

// Start nodes concurrently (it's faster).
exe.submit(new Callable<Object>() {
@Override public Object call() throws Exception {
// All defaults.
GridConfigurationAdapter cfg = new GridConfigurationAdapter();

cfg.setGridName(nodeName);

// Configure in-VM TCP discovery so we don't
// interfere with other grids running on the same network.
GridTcpDiscoverySpi discoSpi = new GridTcpDiscoverySpi();

discoSpi.setIpFinder(ipFinder);

cfg.setDiscoverySpi(discoSpi);

G.start(cfg);

return null;
}
});
}

exe.shutdown();

exe.awaitTermination(20, TimeUnit.SECONDS);

// Get first node.
Grid g = G.grid("jvm-node-0");

// Print out number of nodes in topology.
X.println("Number of nodes in the grid: " + g.nodes().size());

// Wait until Ok is pressed.
JOptionPane.showMessageDialog(
null,
new JComponent[] {
new JLabel("GridGain JVM cloud started."),
new JLabel("Press OK to stop all nodes.")
},
"GridGain",
JOptionPane.INFORMATION_MESSAGE);
}
finally {
G.stopAll(true);
}
}
}
[/source]

That's all there's to it. Enjoy your in-JVM micro cloud!