org.apache.ignite.lang.IgniteFuture Java Examples

The following examples show how to use org.apache.ignite.lang.IgniteFuture. 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: ServiceDeploymentOutsideBaselineTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param staticDeploy If {@code true}, then static deployment will be used instead of a dynamic one.
 * @param nodeNum Nouber of test node.
 * @throws Exception If node failed to start.
 */
private Ignite deployServiceFromNewNode(boolean staticDeploy, int nodeNum) throws Exception {
    Ignite ignite;

    if (staticDeploy) {
        srvcCfg = getClusterSingletonServiceConfiguration();

        ignite = startGrid(nodeNum);
    }
    else {
        ignite = startGrid(nodeNum);

        IgniteFuture<Void> depFut = ignite.services().deployClusterSingletonAsync(SERVICE_NAME, new DummyService());

        depFut.get(10, TimeUnit.SECONDS);
    }

    ignite.cluster().baselineAutoAdjustEnabled(false);

    return ignite;
}
 
Example #2
Source File: IgniteCacheAbstractStopBusySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testPutAsync() throws Exception {
    executeTest(new Callable<Object>() {
        /** {@inheritDoc} */
        @Override public Object call() throws Exception {
            info("Start operation.");

            IgniteFuture f = clientCache().getAndPutAsync(1, 1);

            info("Stop operation.");

            return f.get();
        }
    });
}
 
Example #3
Source File: IgniteComputeConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testBroadcastClosureAsync() throws Exception {
    runTest(closureFactories, new ComputeTest() {
        @Override public void test(Factory factory, Ignite ignite) throws Exception {
            final Collection<Object> resultsAllNull = ignite.compute()
                .broadcast((IgniteClosure<Object, Object>)factory.create(), null);

            assertEquals("Result's size mismatch: job must be run on all server nodes",
                gridCount() - clientsCount(), resultsAllNull.size());

            for (Object o : resultsAllNull)
                assertNull("All results must be null", o);

            IgniteFuture<Collection<Object>> fut = ignite.compute()
                .broadcastAsync((IgniteClosure<Object, Object>)factory.create(), value(0));

            checkResultsClassCount(gridCount() - clientsCount(), fut.get(), value(0).getClass());
        }
    });
}
 
Example #4
Source File: IgniteClusterSnapshotSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** @throws Exception If fails. */
@Test
public void testConcurrentClusterSnapshotFromClient() throws Exception {
    IgniteEx grid = startGridsWithCache(2, dfltCacheCfg, CACHE_KEYS_RANGE);

    IgniteEx clnt = startClientGrid(2);

    IgniteSnapshotManager mgr = snp(grid);
    Function<String, SnapshotSender> old = mgr.localSnapshotSenderFactory();

    BlockingExecutor block = new BlockingExecutor(mgr.snapshotExecutorService());

    mgr.localSnapshotSenderFactory((snpName) ->
        new DelegateSnapshotSender(log, block, old.apply(snpName)));

    IgniteFuture<Void> fut = grid.snapshot().createSnapshot(SNAPSHOT_NAME);

    assertThrowsAnyCause(log,
        () -> clnt.snapshot().createSnapshot(SNAPSHOT_NAME).get(),
        IgniteException.class,
        "Snapshot has not been created");

    block.unblock();
    fut.get();
}
 
Example #5
Source File: IgniteComputeConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testApplyForCollectionAsync() throws Exception {
    runTest(closureFactories, new ComputeTest() {
        @Override public void test(Factory factory, Ignite ignite) throws Exception {
            Collection params = new ArrayList<>(MAX_JOB_COUNT);

            for (int i = 0; i < MAX_JOB_COUNT; ++i) {
                // value(i - 1): use negative argument of the value method to generate nullong value.
                params.add(value(i - 1));
            }

            IgniteClosure c = (IgniteClosure)factory.create();

            // Use type casting to avoid ambiguous for apply(Callable, Object) vs apply(Callable, Collection<Object>).
            IgniteFuture<Collection<Object>> fut = ignite.compute().applyAsync(
                (IgniteClosure<TestObject, Object>)c,
                (Collection<TestObject>)params);

            checkResultsClassCount(MAX_JOB_COUNT - 1, fut.get(), value(0).getClass());
            assertCollectionsEquals("Results value mismatch", createGoldenResults(), fut.get());
        }
    });
}
 
Example #6
Source File: ComputeTaskCancelRemoteSecurityContextCheckTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param isClientInitiator The initiator node is client.
 * @param isClientRmt The remote node is client.
 */
private void prepareAndCheck(boolean isClientInitiator, boolean isClientRmt) throws Exception {
    try {
        IgniteEx srv = startGridAllowAll("srv_init");

        IgniteEx initator = isClientInitiator ? startClientAllowAll("clnt_init") : srv;

        IgniteEx rmt = isClientRmt ? startClientAllowAll("clnt_rmt") : startGridAllowAll("srv_rmt");

        srv.cluster().state(ClusterState.ACTIVE);

        //Checks the case when IgniteFuture#cancel is called.
        checkCancel(initator, rmt, IgniteFuture::cancel);
        //Checks the case when rmt node leaves the cluster.
        checkCancel(initator, rmt, f -> stopGrid(rmt.name(), true));
    }
    finally {
        G.stopAll(true);

        cleanPersistenceDir();
    }
}
 
Example #7
Source File: GatewayProtectedCacheProxy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> IgniteFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync(Map<? extends K, ? extends EntryProcessor<K, V, T>> map, Object... args) throws TransactionException {
    CacheOperationGate opGate = onEnter();

    try {
        return delegate.invokeAllAsync(map, args);
    }
    finally {
        onLeave(opGate);
    }
}
 
Example #8
Source File: AsyncFutureListener.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param lsnr Listener to be called asynchronously.
 * @param exec Executor to process listener.
 */
public AsyncFutureListener(IgniteInClosure<? super IgniteFuture<V>> lsnr, Executor exec) {
    assert lsnr != null;
    assert exec != null;

    this.lsnr = lsnr;
    this.exec = exec;
}
 
Example #9
Source File: ScheduleFutureImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param res Last execution result.
 * @param err Last execution error.
 */
private void notifyListeners(R res, Throwable err) {
    final Collection<IgniteInClosure<? super IgniteFuture<R>>> tmp;

    synchronized (mux) {
        tmp = new ArrayList<>(lsnrs);
    }

    final SchedulerFuture<R> snapshot = snapshot(res, err);

    for (IgniteInClosure<? super IgniteFuture<R>> lsnr : tmp)
        lsnr.apply(snapshot);
}
 
Example #10
Source File: ScheduleFutureImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> IgniteFuture<T> chainAsync(IgniteClosure<? super IgniteFuture<R>, T> doneCb, Executor exec) {
    A.notNull(doneCb, "");
    A.notNull(exec, "exec");

    return chain(doneCb, exec);
}
 
Example #11
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testInvokeAsync() throws Exception {
    runInAllDataModes(new TestRunnable() {
        @Override public void run() throws Exception {
            final Object key1 = key(1);
            final Object key2 = key(2);
            final Object key3 = key(3);

            final Object val1 = value(1);
            final Object val2 = value(2);
            final Object val3 = value(3);

            IgniteCache<Object, Object> cache = jcache();

            cache.put(key2, val1);
            cache.put(key3, val3);

            IgniteFuture<?> fut0 = cache.invokeAsync(key1, INCR_PROCESSOR, dataMode);

            IgniteFuture<?> fut1 = cache.invokeAsync(key2, INCR_PROCESSOR, dataMode);

            IgniteFuture<?> fut2 = cache.invokeAsync(key3, RMV_PROCESSOR);

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

            assertEquals(val1, cache.get(key1));
            assertEquals(val2, cache.get(key2));
            assertNull(cache.get(key3));

            for (int i = 0; i < gridCount(); i++)
                assertNull(jcache(i).localPeek(key3, ONHEAP));
        }
    });
}
 
Example #12
Source File: IgniteCacheProxyImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> IgniteFuture<Map<K, EntryProcessorResult<T>>> invokeAllAsync(Set<? extends K> keys,
    EntryProcessor<K, V, T> entryProcessor, Object... args) {
    IgniteInternalCache<K, V> delegate = getDelegateSafe();

    return createFuture(delegate.invokeAllAsync(keys, entryProcessor, args));
}
 
Example #13
Source File: CacheGetRemoveSkipStoreTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param client Client to test.
 * @param ccfg Cache configuration
 */
public void checkRemoveIsApplied(Ignite client, CacheConfiguration<Integer, Integer> ccfg) {
    // Allow first read.
    readSemaphore = new Semaphore(1);

    IgniteCache<Integer, Integer> cache = client.getOrCreateCache(ccfg);

    try {
        Integer key = 1;

        assertNotNull(cache.get(key));

        Ignite primary = grid(client.affinity(ccfg.getName()).mapKeyToNode(key));

        assertNotNull(primary.cache(ccfg.getName()).localPeek(key));

        // Read-through will be blocked on semaphore.
        IgniteFuture<Integer> getFut = cache.getAsync(key);

        cache.remove(key);

        assertNull(primary.cache(ccfg.getName()).localPeek(key)); // Check that remove actually takes place.

        readSemaphore.release(2);

        assertNotNull(getFut.get());
        assertNotNull(cache.get(key));
        assertNotNull(primary.cache(ccfg.getName()).localPeek(key));
    }
    finally {
        client.destroyCache(ccfg.getName());
    }
}
 
Example #14
Source File: IgniteComputeImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <R> IgniteFuture<R> affinityCallAsync(String cacheName, Object affKey,
    IgniteCallable<R> job) throws IgniteException {
    CU.validateCacheName(cacheName);

    return createFuture(affinityCallAsync0(cacheName, affKey, job));
}
 
Example #15
Source File: IgniteComputeEmptyClusterGroupTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param fut Future.
 */
private void checkFutureFails(final IgniteFuture fut) {
    assertNotNull(fut);

    GridTestUtils.assertThrows(log, new Callable<Void>() {
        @Override public Void call() throws Exception {
            fut.get();

            return null;
        }
    }, ClusterGroupEmptyException.class, null);
}
 
Example #16
Source File: GridServiceProcessorBatchDeploySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param client Client.
 * @param async If {@code true}, then async version of deploy method will be used.
 * @param cfgs Service configurations.
 * @param failingCfg Configuration of the failing service.
 * @throws Exception If failed.
 */
private void assertFailingDeploy(Ignite client, boolean async, List<ServiceConfiguration> cfgs,
    ServiceConfiguration failingCfg) throws Exception {

    IgniteFuture<Void> fut = null;

    if (async)
        fut = client.services().deployAllAsync(cfgs);

    try {
        if (async)
            fut.get();
        else
            client.services().deployAll(cfgs);

        fail("Should never reach here.");
    }
    catch (ServiceDeploymentException e) {
        info("Expected exception: " + e.getMessage());

        Collection<ServiceConfiguration> expFails = Collections.singleton(failingCfg);

        Collection<ServiceConfiguration> actFails = e.getFailedConfigurations();

        // Some cfgs may be lazy. Construct ServiceConfiguration from them for comparison.
        Collection<ServiceConfiguration> actFailsCp = new ArrayList<>(actFails.size());

        for (ServiceConfiguration cfg : actFails)
            actFailsCp.add(copyService(cfg));

        assertEqualsCollections(expFails, actFailsCp);
    }
}
 
Example #17
Source File: GatewayProtectedCacheProxy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public IgniteFuture<Boolean> removeAsync(K key, V oldVal) throws TransactionException {
    CacheOperationGate opGate = onEnter();

    try {
        return delegate.removeAsync(key, oldVal);
    }
    finally {
        onLeave(opGate);
    }
}
 
Example #18
Source File: IgniteCacheManyAsyncOperationsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testManyAsyncOperations() throws Exception {
    try (Ignite client = startClientGrid(gridCount())) {
        assertTrue(client.configuration().isClientMode());

        IgniteCache<Object, Object> cache = client.cache(DEFAULT_CACHE_NAME);

        final int ASYNC_OPS = cache.getConfiguration(CacheConfiguration.class).getMaxConcurrentAsyncOperations();

        log.info("Number of async operations: " + ASYNC_OPS);

        Map<Integer, byte[]> map = new HashMap<>();

        for (int i = 0; i < 100; i++)
            map.put(i, new byte[128]);

        for (int iter = 0; iter < 3; iter++) {
            log.info("Iteration: " + iter);

            List<IgniteFuture<?>> futs = new ArrayList<>(ASYNC_OPS);

            for (int i = 0; i < ASYNC_OPS; i++) {
                futs.add(cache.putAllAsync(map));

                if (i % 50 == 0)
                    log.info("Created futures: " + (i + 1));
            }

            for (int i = 0; i < ASYNC_OPS; i++) {
                IgniteFuture<?> fut = futs.get(i);

                fut.get();

                if (i % 50 == 0)
                    log.info("Done: " + (i + 1));
            }
        }
    }
}
 
Example #19
Source File: AsyncFutureListener.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void apply(final IgniteFuture<V> fut) {
    exec.execute(new Runnable() {
        @Override public void run() {
            lsnr.apply(fut);
        }
    });
}
 
Example #20
Source File: VisorCacheClearTask.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param fut Future to listen.
 * @return {@code true} If future was not completed and this job should holdCC.
 */
private boolean callAsync(IgniteFuture fut) {
    if (fut.isDone())
        return false;

    jobCtx.holdcc();

    fut.listen(lsnr);

    return true;
}
 
Example #21
Source File: IgniteComputeImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <R> IgniteFuture<R> affinityCallAsync(@NotNull Collection<String> cacheNames, int partId,
    IgniteCallable<R> job) throws IgniteException {
    CU.validateCacheNames(cacheNames);

    return createFuture(affinityCallAsync0(cacheNames, partId, job));
}
 
Example #22
Source File: CacheAsyncOperationsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 */
private void async1(IgniteCache<Integer, Integer> cache) {
    cache.put(1, 1);

    latch = new CountDownLatch(1);

    IgniteFuture<?> fut1 = cache.putAsync(0, 0);

    IgniteFuture<?> fut2 = cache.getAndPutAsync(1, 2);

    IgniteFuture<?> fut3 = cache.getAndPutAsync(1, 3);

    assertFalse(fut1.isDone());
    assertFalse(fut2.isDone());
    assertFalse(fut3.isDone());

    latch.countDown();

    try {
        fut1.get();

        fail();
    }
    catch (CacheException e) {
        log.info("Expected error: " + e);
    }

    assertEquals(1, fut2.get());
    assertEquals(2, fut3.get());

    assertNull(cache.get(0));
    assertEquals((Integer)3, cache.get(1));
}
 
Example #23
Source File: GatewayProtectedCacheProxy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public IgniteFuture<Void> removeAllAsync(Set<? extends K> keys) throws TransactionException {
    CacheOperationGate opGate = onEnter();

    try {
        return delegate.removeAllAsync(keys);
    }
    finally {
        onLeave(opGate);
    }
}
 
Example #24
Source File: GridClosureProcessorSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param idx Node index.
 * @param job Callable job.
 * @param p Optional node predicate.
 * @return Future object.
 */
private IgniteFuture<Collection<Integer>> broadcast(int idx, IgniteCallable<Integer> job,
    @Nullable IgnitePredicate<ClusterNode> p) {
    assert idx >= 0 && idx < NODES_CNT;
    assert job != null;

    execCntr.set(0);

    IgniteCompute comp = p != null ? compute(grid(idx).cluster().forPredicate(p)) : grid(idx).compute();

    return comp.broadcastAsync(job);
}
 
Example #25
Source File: IgniteComputeImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public <R1, R2> IgniteFuture<R2> callAsync(Collection<? extends IgniteCallable<R1>> jobs,
    IgniteReducer<R1, R2> rdc) throws IgniteException {
    return (IgniteFuture<R2>)createFuture(callAsync0(jobs, rdc));
}
 
Example #26
Source File: IgniteFutureImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> IgniteFuture<T> chain(final IgniteClosure<? super IgniteFuture<V>, T> doneCb) {
    return new IgniteFutureImpl<>(chainInternal(doneCb, null));
}
 
Example #27
Source File: IgniteCacheProcessProxy.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public IgniteFuture<CacheEntry<K, V>> getEntryAsync(K key) {
    return compute.callAsync(new GetEntryTask<K, V>(cacheName, isAsync, key));
}
 
Example #28
Source File: CacheAffinitySharedManager.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) {
    Iterator<Integer> it = grpHolders.keySet().iterator();

    while (it.hasNext()) {
        int grpId = it.next();

        it.remove();

        cctx.io().removeHandler(true, grpId, GridDhtAffinityAssignmentResponse.class);
    }

    assert grpHolders.isEmpty();

    super.onDisconnected(reconnectFut);
}
 
Example #29
Source File: IgniteComputeImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public IgniteFuture<Void> broadcastAsync(IgniteRunnable job) throws IgniteException {
    return (IgniteFuture<Void>)createFuture(broadcastAsync0(job));
}
 
Example #30
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();
    }
}