Repository: incubator-ignite
Updated Branches:
  refs/heads/ignite-45 08e65e9d8 -> 4230e03a1


# IGNITE-45 - Examples


Project: http://git-wip-us.apache.org/repos/asf/incubator-ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ignite/commit/4230e03a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ignite/tree/4230e03a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ignite/diff/4230e03a

Branch: refs/heads/ignite-45
Commit: 4230e03a1502840b4000eb3ad01cc003092a2df2
Parents: 08e65e9
Author: Valentin Kulichenko <vkuliche...@gridgain.com>
Authored: Sat Mar 21 18:08:41 2015 -0700
Committer: Valentin Kulichenko <vkuliche...@gridgain.com>
Committed: Sat Mar 21 18:08:41 2015 -0700

----------------------------------------------------------------------
 .../java8/datagrid/CacheAffinityExample.java    | 131 +++++++++++++++++++
 .../java8/datagrid/CacheApiExample.java         | 123 +++++++++++++++++
 2 files changed, 254 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/4230e03a/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheAffinityExample.java
----------------------------------------------------------------------
diff --git 
a/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheAffinityExample.java
 
b/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheAffinityExample.java
new file mode 100644
index 0000000..4aedd5a
--- /dev/null
+++ 
b/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheAffinityExample.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.examples.java8.datagrid;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.cluster.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.examples.*;
+import org.apache.ignite.lang.*;
+
+import java.util.*;
+
+/**
+ * This example demonstrates the simplest code that populates the distributed 
cache
+ * and co-locates simple closure execution with each key. The goal of this 
particular
+ * example is to provide the simplest code example of this logic.
+ * <p>
+ * Remote nodes should always be started with special configuration file which
+ * enables P2P class loading: {@code 'ignite.{sh|bat} 
examples/config/example-ignite.xml'}.
+ * <p>
+ * Alternatively you can run {@link ExampleNodeStartup} in another JVM which 
will
+ * start node with {@code examples/config/example-ignite.xml} configuration.
+ */
+public final class CacheAffinityExample {
+    /** Cache name. */
+    private static final String CACHE_NAME = 
CacheAffinityExample.class.getSimpleName();
+
+    /** Number of keys. */
+    private static final int KEY_CNT = 20;
+
+    /**
+     * Executes example.
+     *
+     * @param args Command line arguments, none required.
+     * @throws IgniteException If example execution failed.
+     */
+    public static void main(String[] args) throws IgniteException {
+        try (Ignite ignite = 
Ignition.start("examples/config/example-ignite.xml")) {
+            System.out.println();
+            System.out.println(">>> Cache affinity example started.");
+
+            CacheConfiguration<Integer, String> cfg = new 
CacheConfiguration<>();
+
+            cfg.setCacheMode(CacheMode.PARTITIONED);
+            cfg.setName(CACHE_NAME);
+
+            try (IgniteCache<Integer, String> cache = ignite.createCache(cfg)) 
{
+                for (int i = 0; i < KEY_CNT; i++)
+                    cache.put(i, Integer.toString(i));
+
+                // Co-locates jobs with data using 
IgniteCompute.affinityRun(...) method.
+                visitUsingAffinityRun();
+
+                // Co-locates jobs with data using 
IgniteCluster.mapKeysToNodes(...) method.
+                visitUsingMapKeysToNodes();
+            }
+        }
+    }
+
+    /**
+     * Collocates jobs with keys they need to work on using
+     * {@link IgniteCompute#affinityRun(String, Object, IgniteRunnable)} 
method.
+     */
+    private static void visitUsingAffinityRun() {
+        Ignite ignite = Ignition.ignite();
+
+        final IgniteCache<Integer, String> cache = ignite.jcache(CACHE_NAME);
+
+        for (int i = 0; i < KEY_CNT; i++) {
+            int key = i;
+
+            // This runnable will execute on the remote node where
+            // data with the given key is located. Since it will be co-located
+            // we can use local 'peek' operation safely.
+            ignite.compute().affinityRun(CACHE_NAME, key,
+                () -> System.out.println("Co-located using affinityRun [key= " 
+ key + ", value=" + cache.localPeek(key) + ']'));
+        }
+    }
+
+    /**
+     * Collocates jobs with keys they need to work on using {@link 
IgniteCluster#mapKeysToNodes(String, Collection)}
+     * method. The difference from {@code affinityRun(...)} method is that 
here we process multiple keys
+     * in a single job.
+     */
+    private static void visitUsingMapKeysToNodes() {
+        final Ignite ignite = Ignition.ignite();
+
+        Collection<Integer> keys = new ArrayList<>(KEY_CNT);
+
+        for (int i = 0; i < KEY_CNT; i++)
+            keys.add(i);
+
+        // Map all keys to nodes.
+        Map<ClusterNode, Collection<Integer>> mappings = 
ignite.cluster().mapKeysToNodes(CACHE_NAME, keys);
+
+        for (Map.Entry<ClusterNode, Collection<Integer>> mapping : 
mappings.entrySet()) {
+            ClusterNode node = mapping.getKey();
+
+            final Collection<Integer> mappedKeys = mapping.getValue();
+
+            if (node != null) {
+                // Bring computations to the nodes where the data resides 
(i.e. collocation).
+                ignite.compute(ignite.cluster().forNode(node)).run(() -> {
+                    IgniteCache<Integer, String> cache = 
ignite.jcache(CACHE_NAME);
+
+                    // Peek is a local memory lookup, however, value should 
never be 'null'
+                    // as we are co-located with node that has a given key.
+                    for (Integer key : mappedKeys)
+                        System.out.println("Co-located using mapKeysToNodes 
[key= " + key +
+                            ", value=" + cache.localPeek(key) + ']');
+                });
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/4230e03a/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheApiExample.java
----------------------------------------------------------------------
diff --git 
a/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheApiExample.java
 
b/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheApiExample.java
new file mode 100644
index 0000000..597a841
--- /dev/null
+++ 
b/examples/src/main/java8/org/apache/ignite/examples/java8/datagrid/CacheApiExample.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.examples.java8.datagrid;
+
+import org.apache.ignite.*;
+import org.apache.ignite.cache.*;
+import org.apache.ignite.configuration.*;
+import org.apache.ignite.examples.*;
+import org.apache.ignite.lang.*;
+
+import java.util.concurrent.*;
+
+/**
+ * This example demonstrates some of the cache rich API capabilities.
+ * <p>
+ * Remote nodes should always be started with special configuration file which
+ * enables P2P class loading: {@code 'ignite.{sh|bat} 
examples/config/example-ignite.xml'}.
+ * <p>
+ * Alternatively you can run {@link ExampleNodeStartup} in another JVM which 
will
+ * start node with {@code examples/config/example-ignite.xml} configuration.
+ */
+public class CacheApiExample {
+    /** Cache name. */
+    private static final String CACHE_NAME = 
CacheApiExample.class.getSimpleName();
+
+    /**
+     * Executes example.
+     *
+     * @param args Command line arguments, none required.
+     * @throws IgniteException If example execution failed.
+     */
+    public static void main(String[] args) throws IgniteException {
+        try (Ignite ignite = 
Ignition.start("examples/config/example-ignite.xml")) {
+            System.out.println();
+            System.out.println(">>> Cache API example started.");
+
+            CacheConfiguration<Integer, String> cfg = new 
CacheConfiguration<>();
+
+            cfg.setCacheMode(CacheMode.PARTITIONED);
+            cfg.setName(CACHE_NAME);
+
+            try (IgniteCache<Integer, String> cache = ignite.createCache(cfg)) 
{
+                // Demonstrate atomic map operations.
+                atomicMapOperations(cache);
+            }
+        }
+    }
+
+    /**
+     * Demonstrates cache operations similar to {@link ConcurrentMap} API. 
Note that
+     * cache API is a lot richer than the JDK {@link ConcurrentMap}.
+     *
+     * @throws IgniteException If failed.
+     */
+    private static void atomicMapOperations(final IgniteCache<Integer, String> 
cache) throws IgniteException {
+        System.out.println();
+        System.out.println(">>> Cache atomic map operation examples.");
+
+        // Put and return previous value.
+        String v = cache.getAndPut(1, "1");
+        assert v == null;
+
+        // Put and do not return previous value (all methods ending with 'x' 
return boolean).
+        // Performs better when previous value is not needed.
+        cache.put(2, "2");
+
+        // Put asynchronously.
+        final IgniteCache<Integer, String> asyncCache = cache.withAsync();
+
+        asyncCache.put(3, "3");
+
+        asyncCache.get(3);
+
+        IgniteFuture<String> fut = asyncCache.future();
+
+        //Asynchronously wait for result.
+        fut.listen(fut1 -> {
+            try {
+                System.out.println("Put operation completed [previous-value=" 
+ fut1.get() + ']');
+            }
+            catch (IgniteException e) {
+                e.printStackTrace();
+            }
+        });
+
+        // Put-if-absent.
+        boolean b1 = cache.putIfAbsent(4, "4");
+        boolean b2 = cache.putIfAbsent(4, "44");
+        assert b1 && !b2;
+
+        // Invoke - assign new value based on previous value.
+        cache.put(6, "6");
+
+        cache.invoke(6, (entry, args) -> {
+            String val = entry.getValue();
+
+            entry.setValue(val + "6"); // Set new value based on previous 
value.
+
+            return null;
+        });
+
+        // Replace.
+        cache.put(7, "7");
+        b1 = cache.replace(7, "7", "77");
+        b2 = cache.replace(7, "7", "777");
+        assert b1 & !b2;
+    }
+}

Reply via email to