Take a look for example at how you can *recursively* calculate Fibonacci sequence for number 10 in GridGain 3.0 (this is not the most effective implementation, but bare with me for now):
final Grid g = G.start(); // Start grid. int fib = g.call(UNICAST, new GridClosureX<Integer, Integer>() { @Override public Integer applyx(Integer n) throws GridException { return n == 0 ? 0 : n <= 2 ? 1 : g.call(UNICAST, this, n - 1) + g.call(UNICAST, this, n - 2); } }, 10);Things to notice in the above coding snippet:
- GridClosureX is just a function which will be executed on the remote grid or cloud (suffix 'X' means that it throws GridException).
- There is no deployment step - GridGain auto-deploys your code on participating nodes on-demand (pretty cool).
- We are reusing the same grid variable "g" in local and remote code (even cooler, but it gets better).
- Note how we are re-executing the same closure from remote nodes *recursively* by passing "this" into "g.call(..)" method!!!
Let's get a little fancier and introduce caching of calculated Fibonacci numbers on remote nodes. Also let's switch to using BigInteger so we can handle really large numbers:
BigInteger fib = g.call(UNICAST, new GridClosureX<Long, BigInteger>() { @Override public BigInteger applyx(Long n) throws GridException { System.out.println("Starting fibonacci execution for number: " + n); // Make sure n is not negative. n = Math.abs(n); if (n == 0) { return BigInteger.ZERO; } if (n <= 2) { return BigInteger.ONE; } // Node-local storage is provided by Grid.nodeLocal() method. GridNodeLocal<Long, BigInteger> nodeLocal = g.nodeLocal(); // Check if value is cached in node-local store first. BigInteger n1 = nodeLocal.get(n - 1); // If value is not cached in node-local store, then // compute it and cache it. if (n1 == null) { // Nested recursive distributed execution on the grid. nodeLocal.putIfAbsent(n - 1, n1 = g.call(UNICAST, this, n - 1, p)); } // Check if value is cached in node-local store first. BigInteger n2 = nodeLocal.get(n - 2); // If value is not cached in node-local store, then // compute it and cache it. if (n2 == null) { // Nested recursive distributed execution on the grid. nodeLocal.putIfAbsent(n - 2, n2 = g.call(UNICAST, this, n - 2, p)); } return n1.add(n2); } }, 100);This code snippet is pretty similar to the first one, except that it caches already calculated values directly on remote nodes, so it gets smarter as it progresses. If you run it twice for the same value, no recursion will happen the second time at all, and you will get result immediately from node-local store. All we need to do now is just startup a few grid nodes and give it a go. The result for Fibonacci(100) is '354224848179261915075' by the way.
Now I want you to stop for a second and think about what we have been able to achieve just in a few lines of code above.
This example, along with many others, is shipped with GridGain. I invite you to download it and see it for yourself.
Add a comment