Java Code Examples for org.apache.ignite.IgniteCache#withAsync()

The following examples show how to use org.apache.ignite.IgniteCache#withAsync() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception In case of error.
 */
@Test
public void testRemoveAllAsyncOld() throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    checkSize(F.asSet("key1", "key2", "key3"));

    cacheAsync.removeAll(F.asSet("key1", "key2"));

    assertNull(cacheAsync.future().get());

    checkSize(F.asSet("key3"));

    checkContainsKey(false, "key1");
    checkContainsKey(false, "key2");
    checkContainsKey(true, "key3");
}
 
Example 2
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception In case of error.
 */
@Test
public void testRemoveAllAsyncOld() throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    checkSize(F.asSet("key1", "key2", "key3"));

    cacheAsync.removeAll(F.asSet("key1", "key2"));

    assertNull(cacheAsync.future().get());

    checkSize(F.asSet("key3"));

    checkContainsKey(false, "key1");
    checkContainsKey(false, "key2");
    checkContainsKey(true, "key3");
}
 
Example 3
Source File: IgnteCacheClientWriteBehindStoreNonCoalescingTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Update random key in async mode.
 *
 * @param cache Cache to use.
 * @return IgniteFuture.
 */
private IgniteFuture<?> updateKey(IgniteCache<Integer, Integer> cache) {
    IgniteCache asyncCache = cache.withAsync();

    // Using EntryProcessor.invokeAll to increment every value in place.
    asyncCache.invoke(rnd.nextInt(100), new EntryProcessor<Integer, Integer, Object>() {
        @Override public Object process(MutableEntry<Integer, Integer> entry, Object... arguments)
            throws EntryProcessorException {
            entry.setValue(entry.getValue() + 1);

            return null;
        }
    });

    return asyncCache.future();
}
 
Example 4
Source File: HelloIgniteAsyn.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
    System.out.println("Hello Ignite Asynchronous!!");
    // create a new instance of TCP Discovery SPI
    TcpDiscoverySpi spi = new TcpDiscoverySpi();
    // create a new instance of tcp discovery multicast ip finder
    TcpDiscoveryMulticastIpFinder tcMp = new TcpDiscoveryMulticastIpFinder();
    tcMp.setAddresses(Arrays.asList("localhost")); // change your IP address here
    // set the multi cast ip finder for spi
    spi.setIpFinder(tcMp);
    // create new ignite configuration
    IgniteConfiguration cfg = new IgniteConfiguration();
    cfg.setClientMode(false);
    // set the discovery spi to ignite configuration
    cfg.setDiscoverySpi(spi);
    // Start ignite
    Ignite ignite = Ignition.start(cfg);

    // get or create cache
    IgniteCache<Integer, String> cache = ignite.getOrCreateCache("testCache");
    // get an asynchronous cache
    IgniteCache<Integer, String> asynCache = cache.withAsync();

    // put some cache elements
    for(int i = 1; i <= 100; i++){
        cache.put(i, Integer.toString(i));
    }

    String val = asynCache.withAsync().get(1);
    System.out.println("Non future call:" + val);
    IgniteFuture<String> igniteFuture = asynCache.future();



    igniteFuture.listen(f-> System.out.println("Cache Value:" + f.get()));
    ignite.close();

}
 
Example 5
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests invokeAll method for map of pairs (key, entryProcessor).
 *
 * @param cache Cache.
 * @param required Expected injected resources.
 * @param async Use async API.
 * @param oldAsync Use old async API.
 */
private void checkResourceInjectionOnInvokeAllMap(IgniteCache<String, Integer> cache,
    Collection<ResourceType> required, boolean async, boolean oldAsync) {
    Map<String, EntryProcessorResult<Integer>> results;

    Map<String, EntryProcessor<String, Integer, Integer>> map = new HashMap<>();

    map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor());
    map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor());
    map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor());
    map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor());

    if (async) {
        if (oldAsync) {
            IgniteCache<String, Integer> acache = cache.withAsync();

            acache.invokeAll(map);

            results = acache.<Map<String, EntryProcessorResult<Integer>>>future().get();
        }
        else
            results = cache.invokeAllAsync(map).get();
    }
    else
        results = cache.invokeAll(map);

    assertEquals(map.size(), results.size());

    for (EntryProcessorResult<Integer> res : results.values()) {
        Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(res.get()).notInjected(required);

        if (!notInjected.isEmpty())
            fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray()));
    }
}
 
Example 6
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests invokeAll method for set of keys.
 *
 * @param cache Cache.
 * @param required Expected injected resources.
 * @param async Use async API.
 * @param oldAsync Use old async API.
 */
private void checkResourceInjectionOnInvokeAll(IgniteCache<String, Integer> cache,
    Collection<ResourceType> required, boolean async, boolean oldAsync) {
    Set<String> keys = new HashSet<>(Arrays.asList(UUID.randomUUID().toString(),
        UUID.randomUUID().toString(),
        UUID.randomUUID().toString(),
        UUID.randomUUID().toString()));

    Map<String, EntryProcessorResult<Integer>> results;

    if (async) {
        if (oldAsync) {
            IgniteCache<String, Integer> acache = cache.withAsync();

            acache.invokeAll(keys, new ResourceInjectionEntryProcessor());

            results = acache.<Map<String, EntryProcessorResult<Integer>>>future().get();
        }
        else
            results = cache.invokeAllAsync(keys, new ResourceInjectionEntryProcessor()).get();
    }
    else
        results = cache.invokeAll(keys, new ResourceInjectionEntryProcessor());

    assertEquals(keys.size(), results.size());

    for (EntryProcessorResult<Integer> res : results.values()) {
        Collection<ResourceType> notInjected1 = ResourceInfoSet.valueOf(res.get()).notInjected(required);

        if (!notInjected1.isEmpty())
            fail("Can't inject resource(s): " + Arrays.toString(notInjected1.toArray()));
    }
}
 
Example 7
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests invoke for single key.
 *
 * @param cache Cache.
 * @param required Expected injected resources.
 * @param async Use async API.
 * @param oldAsync Use old async API.
 */
private void checkResourceInjectionOnInvoke(IgniteCache<String, Integer> cache,
    Collection<ResourceType> required, boolean async, boolean oldAsync) {

    String key = UUID.randomUUID().toString();

    Integer flags;

    if (async) {
        if (oldAsync) {
            IgniteCache<String, Integer> acache = cache.withAsync();

            acache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor());

            flags = acache.<Integer>future().get();
        }
        else
            flags = cache.invokeAsync(key,
                new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor()).get();
    }
    else
        flags = cache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor());

    if (cache.isAsync())
        flags = cache.<Integer>future().get();

    assertTrue("Processor result is null", flags != null);

    Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(flags).notInjected(required);

    if (!notInjected.isEmpty())
        fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray()));
}
 
Example 8
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception In case of error.
 */
@Test
public void testGetAndPutAsyncOld() throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    cache.put("key1", 1);
    cache.put("key2", 2);

    cacheAsync.getAndPut("key1", 10);

    IgniteFuture<Integer> fut1 = cacheAsync.future();

    cacheAsync.getAndPut("key2", 11);

    IgniteFuture<Integer> fut2 = cacheAsync.future();

    assertEquals((Integer)1, fut1.get(5000));
    assertEquals((Integer)2, fut2.get(5000));

    assertEquals((Integer)10, cache.get("key1"));
    assertEquals((Integer)11, cache.get("key2"));
}
 
Example 9
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testGetAndPutIfAbsentAsyncOld() throws Exception {
    Transaction tx = txShouldBeUsed() ? transactions().txStart() : null;

    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    try {
        cacheAsync.getAndPutIfAbsent("key", 1);

        IgniteFuture<Integer> fut1 = cacheAsync.future();

        assertNull(fut1.get());
        assertEquals((Integer)1, cache.get("key"));

        cacheAsync.getAndPutIfAbsent("key", 2);

        IgniteFuture<Integer> fut2 = cacheAsync.future();

        assertEquals((Integer)1, fut2.get());
        assertEquals((Integer)1, cache.get("key"));

        if (tx != null)
            tx.commit();
    }
    finally {
        if (tx != null)
            tx.close();
    }

    if (!storeEnabled())
        return;

    // Check swap.
    cache.put("key2", 1);

    cache.localEvict(Collections.singleton("key2"));

    if (!isLoadPreviousValue())
        cache.get("key2");

    cacheAsync.getAndPutIfAbsent("key2", 3);

    assertEquals((Integer)1, cacheAsync.<Integer>future().get());

    // Check db.
    if (storeEnabled() && isLoadPreviousValue() && !isMultiJvm()) {
        putToStore("key3", 3);

        cacheAsync.getAndPutIfAbsent("key3", 4);

        assertEquals((Integer)3, cacheAsync.<Integer>future().get());
    }

    cache.localEvict(Collections.singleton("key2"));

    if (!isLoadPreviousValue())
        cache.get("key2");

    // Same checks inside tx.
    tx = txShouldBeUsed() ? transactions().txStart() : null;

    try {
        cacheAsync.getAndPutIfAbsent("key2", 3);

        assertEquals(1, cacheAsync.future().get());

        if (tx != null)
            tx.commit();

        assertEquals((Integer)1, cache.get("key2"));
    }
    finally {
        if (tx != null)
            tx.close();
    }
}
 
Example 10
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param async If {@code true} uses asynchronous operation.
 * @param oldAsync Use old async API.
 * @throws Exception In case of error.
 */
private void globalRemoveAll(boolean async, boolean oldAsync) throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    checkSize(F.asSet("key1", "key2", "key3"));

    IgniteCache<String, Integer> asyncCache = cache.withAsync();

    if (async) {
        if (oldAsync) {
            asyncCache.removeAll(F.asSet("key1", "key2"));

            asyncCache.future().get();
        }
        else
            cache.removeAllAsync(F.asSet("key1", "key2")).get();
    }
    else
        cache.removeAll(F.asSet("key1", "key2"));

    checkSize(F.asSet("key3"));

    checkContainsKey(false, "key1");
    checkContainsKey(false, "key2");
    checkContainsKey(true, "key3");

    // Put values again.
    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    if (async) {
        if (oldAsync) {
            IgniteCache asyncCache0 = jcache(gridCount() > 1 ? 1 : 0).withAsync();

            asyncCache0.removeAll();

            asyncCache0.future().get();
        }
        else
            jcache(gridCount() > 1 ? 1 : 0).removeAllAsync().get();
    }
    else
        jcache(gridCount() > 1 ? 1 : 0).removeAll();

    assertEquals(0, cache.localSize());
    long entryCnt = hugeRemoveAllEntryCount();

    for (int i = 0; i < entryCnt; i++)
        cache.put(String.valueOf(i), i);

    for (int i = 0; i < entryCnt; i++)
        assertEquals(Integer.valueOf(i), cache.get(String.valueOf(i)));

    if (async) {
        if (oldAsync) {
            asyncCache.removeAll();

            asyncCache.future().get();
        }
        else
            cache.removeAllAsync().get();
    }
    else
        cache.removeAll();

    for (int i = 0; i < entryCnt; i++)
        assertNull(cache.get(String.valueOf(i)));
}
 
Example 11
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param async Use async API.
 * @param oldAsync Uase old style async API.
 * @throws Exception If failed.
 */
private void checkGetOutTx(boolean async, boolean oldAsync) throws Exception {
    final AtomicInteger lockEvtCnt = new AtomicInteger();

    IgnitePredicate<Event> lsnr = new IgnitePredicate<Event>() {
        @Override public boolean apply(Event evt) {
            lockEvtCnt.incrementAndGet();

            return true;
        }
    };

    try {
        IgniteCache<String, Integer> cache = grid(0).cache(cacheName()).withAllowAtomicOpsInTx();

        List<String> keys = primaryKeysForCache(0, 2, 1);

        assertEquals(2, keys.size());

        cache.put(keys.get(0), 0);
        cache.put(keys.get(1), 1);

        grid(0).events().localListen(lsnr, EVT_CACHE_OBJECT_LOCKED, EVT_CACHE_OBJECT_UNLOCKED);

        if (async && oldAsync)
            cache = cache.withAsync();

        try (Transaction tx = transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
            Integer val0;

            if (async) {
                if (oldAsync) {
                    cache.get(keys.get(0));

                    val0 = cache.<Integer>future().get();
                }
                else
                    val0 = cache.getAsync(keys.get(0)).get();
            }
            else
                val0 = cache.get(keys.get(0));

            assertEquals(0, val0.intValue());

            Map<String, Integer> allOutTx;

            if (async) {
                if (oldAsync) {
                    cache.getAllOutTx(F.asSet(keys.get(1)));

                    allOutTx = cache.<Map<String, Integer>>future().get();
                }
                else
                    allOutTx = cache.getAllOutTxAsync(F.asSet(keys.get(1))).get();
            }
            else
                allOutTx = cache.getAllOutTx(F.asSet(keys.get(1)));

            assertEquals(1, allOutTx.size());

            assertTrue(allOutTx.containsKey(keys.get(1)));

            assertEquals(1, allOutTx.get(keys.get(1)).intValue());
        }

        assertTrue(GridTestUtils.waitForCondition(new PA() {
            @Override public boolean apply() {
                info("Lock event count: " + lockEvtCnt.get());
                if (atomicityMode() == ATOMIC)
                    return lockEvtCnt.get() == 0;

                if (cacheMode() == PARTITIONED && nearEnabled()) {
                    if (!grid(0).configuration().isClientMode())
                        return lockEvtCnt.get() == 4;
                }

                return lockEvtCnt.get() == 2;
            }
        }, 15000));
    }
    finally {
        grid(0).events().stopLocalListen(lsnr, EVT_CACHE_OBJECT_LOCKED, EVT_CACHE_OBJECT_UNLOCKED);
    }
}
 
Example 12
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception In case of error.
 */
@Test
public void testGetAndPutAsyncOld() throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    cache.put("key1", 1);
    cache.put("key2", 2);

    cacheAsync.getAndPut("key1", 10);

    IgniteFuture<Integer> fut1 = cacheAsync.future();

    cacheAsync.getAndPut("key2", 11);

    IgniteFuture<Integer> fut2 = cacheAsync.future();

    assertEquals((Integer)1, fut1.get(5000));
    assertEquals((Integer)2, fut2.get(5000));

    assertEquals((Integer)10, cache.get("key1"));
    assertEquals((Integer)11, cache.get("key2"));
}
 
Example 13
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testGetAndPutIfAbsentAsyncOld() throws Exception {
    Transaction tx = txShouldBeUsed() ? transactions().txStart() : null;

    IgniteCache<String, Integer> cache = jcache();

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    try {
        cacheAsync.getAndPutIfAbsent("key", 1);

        IgniteFuture<Integer> fut1 = cacheAsync.future();

        assertNull(fut1.get());
        assertEquals((Integer)1, cache.get("key"));

        cacheAsync.getAndPutIfAbsent("key", 2);

        IgniteFuture<Integer> fut2 = cacheAsync.future();

        assertEquals((Integer)1, fut2.get());
        assertEquals((Integer)1, cache.get("key"));

        if (tx != null)
            tx.commit();
    }
    finally {
        if (tx != null)
            tx.close();
    }

    // Check swap.
    cache.put("key2", 1);

    cache.localEvict(Collections.singleton("key2"));

    cacheAsync.getAndPutIfAbsent("key2", 3);

    assertEquals((Integer)1, cacheAsync.<Integer>future().get());

    // Check db.
    if (!isMultiJvm()) {
        storeStgy.putToStore("key3", 3);

        cacheAsync.getAndPutIfAbsent("key3", 4);

        assertEquals((Integer)3, cacheAsync.<Integer>future().get());
    }

    cache.localEvict(Collections.singleton("key2"));

    // Same checks inside tx.
    tx = txShouldBeUsed() ? transactions().txStart() : null;

    try {
        cacheAsync.getAndPutIfAbsent("key2", 3);

        assertEquals(1, cacheAsync.future().get());

        if (tx != null)
            tx.commit();

        assertEquals((Integer)1, cache.get("key2"));
    }
    finally {
        if (tx != null)
            tx.close();
    }
}
 
Example 14
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param async If {@code true} uses asynchronous operation.
 * @throws Exception In case of error.
 */
private void globalRemoveAllOld(boolean async) throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    checkSize(F.asSet("key1", "key2", "key3"));

    IgniteCache<String, Integer> asyncCache = cache.withAsync();

    if (async) {
        asyncCache.removeAll(F.asSet("key1", "key2"));

        asyncCache.future().get();
    }
    else
        cache.removeAll(F.asSet("key1", "key2"));

    checkSize(F.asSet("key3"));

    checkContainsKey(false, "key1");
    checkContainsKey(false, "key2");
    checkContainsKey(true, "key3");

    // Put values again.
    cache.put("key1", 1);
    cache.put("key2", 2);
    cache.put("key3", 3);

    if (async) {
        IgniteCache<String, Integer> asyncCache0 = jcache(gridCount() > 1 ? 1 : 0).withAsync();

        asyncCache0.removeAll();

        asyncCache0.future().get();
    }
    else
        jcache(gridCount() > 1 ? 1 : 0).removeAll();

    assertEquals(0, cache.localSize());
    long entryCnt = hugeRemoveAllEntryCount();

    for (int i = 0; i < entryCnt; i++)
        cache.put(String.valueOf(i), i);

    for (int i = 0; i < entryCnt; i++)
        assertEquals(Integer.valueOf(i), cache.get(String.valueOf(i)));

    if (async) {
        asyncCache.removeAll();

        asyncCache.future().get();
    }
    else
        cache.removeAll();

    for (int i = 0; i < entryCnt; i++)
        assertNull(cache.get(String.valueOf(i)));
}
 
Example 15
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testInvokeAsyncOld() throws Exception {
    IgniteCache<String, Integer> cache = jcache();

    cache.put("key2", 1);
    cache.put("key3", 3);

    IgniteCache<String, Integer> cacheAsync = cache.withAsync();

    assertNull(cacheAsync.invoke("key1", INCR_PROCESSOR));

    IgniteFuture<?> fut0 = cacheAsync.future();

    assertNull(cacheAsync.invoke("key2", INCR_PROCESSOR));

    IgniteFuture<?> fut1 = cacheAsync.future();

    assertNull(cacheAsync.invoke("key3", RMV_PROCESSOR));

    IgniteFuture<?> fut2 = cacheAsync.future();

    fut0.get();
    fut1.get();
    fut2.get();

    assertEquals((Integer)1, cache.get("key1"));
    assertEquals((Integer)2, cache.get("key2"));
    assertNull(cache.get("key3"));

    for (int i = 0; i < gridCount(); i++)
        assertNull(jcache(i).localPeek("key3", ONHEAP));
}