Java Code Examples for org.apache.ignite.Ignite#transactions()

The following examples show how to use org.apache.ignite.Ignite#transactions() . 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: CacheMvccTransactionsTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if failed.
 */
@Test
public void testEmptyTx() throws Exception {
    Ignite node = startGrids(2);

    IgniteCache cache = node.createCache(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, DFLT_PARTITION_COUNT));

    cache.putAll(Collections.emptyMap());

    IgniteTransactions txs = node.transactions();
    try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
        tx.commit();
    }
    finally {
        stopAllGrids();
    }
}
 
Example 2
Source File: GridTransformSpringInjectionSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testTransformResourceInjection() throws Exception {
    Ignite grid = grid(0);

    IgniteCache<String, Integer> cache = grid.createCache(cacheConfiguration(ATOMIC));

    try {
        doTransformResourceInjection(cache);
    }
    finally {
        cache.destroy();
    }

    cache = grid.createCache(cacheConfiguration(TRANSACTIONAL));

    try {
        doTransformResourceInjection(cache);

        for (TransactionConcurrency concurrency : TransactionConcurrency.values()) {
            for (TransactionIsolation isolation : TransactionIsolation.values()) {
                IgniteTransactions txs = grid.transactions();

                try (Transaction tx = txs.txStart(concurrency, isolation)) {
                    doTransformResourceInjection(cache);

                    tx.commit();
                }
            }
        }
    }
    finally {
        cache.destroy();
    }
}
 
Example 3
Source File: IndexingSpiQuerySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testIndexingSpiFailure() throws Exception {
    indexingSpi = new MyBrokenIndexingSpi();

    Ignite ignite = startGrid(0);

    CacheConfiguration<Integer, Integer> ccfg = cacheConfiguration(DEFAULT_CACHE_NAME);

    ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);

    final IgniteCache<Integer, Integer> cache = ignite.createCache(ccfg);

    final IgniteTransactions txs = ignite.transactions();

    for (final TransactionConcurrency concurrency : TransactionConcurrency.values()) {
        for (final TransactionIsolation isolation : TransactionIsolation.values()) {
            System.out.println("Run in transaction: " + concurrency + " " + isolation);

            GridTestUtils.assertThrowsWithCause(new Callable<Void>() {
                @Override public Void call() throws Exception {
                    Transaction tx;

                    try (Transaction tx0 = tx = txs.txStart(concurrency, isolation)) {
                        cache.put(1, 1);

                        tx0.commit();
                    }

                    assertEquals(TransactionState.ROLLED_BACK, tx.state());
                    return null;
                }
            }, IgniteTxHeuristicCheckedException.class);
        }
    }
}
 
Example 4
Source File: CacheSerializableTransactionsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testTxCommitReadWriteTwoNodes() throws Exception {
    Ignite ignite0 = ignite(0);

    final IgniteTransactions txs = ignite0.transactions();

    for (CacheConfiguration<Integer, Integer> ccfg : cacheConfigurations()) {
        logCacheInfo(ccfg);

        try {
            IgniteCache<Integer, Integer> cache = ignite0.createCache(ccfg);

            Integer key0 = primaryKey(ignite(0).cache(DEFAULT_CACHE_NAME));
            Integer key1 = primaryKey(ignite(1).cache(DEFAULT_CACHE_NAME));

            try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                cache.put(key0, key0);

                cache.get(key1);

                tx.commit();
            }
        }
        finally {
            destroyCache(ccfg.getName());
        }
    }
}
 
Example 5
Source File: IgniteCacheThreadLocalTxTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param node Node.
 */
private void checkNoTx(Ignite node) {
    IgniteTransactions txs = node.transactions();

    assertNull(txs.tx());
    assertNull(((IgniteKernal)node).context().cache().context().tm().tx());
}
 
Example 6
Source File: GridCacheAbstractFullApiSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ignite Node.
 * @param cache Cache.
 * @param async Use async API.
 * @param oldAsync Use old async API.
 * @throws Exception If failed.
 */
private void doTransformResourceInjectionInTx(Ignite ignite, IgniteCache<String, Integer> cache, boolean async,
    boolean oldAsync) throws Exception {
    for (TransactionConcurrency concurrency : TransactionConcurrency.values()) {
        for (TransactionIsolation isolation : TransactionIsolation.values()) {
            IgniteTransactions txs = ignite.transactions();

            try (Transaction tx = txs.txStart(concurrency, isolation)) {
                doTransformResourceInjection(ignite, cache, async, oldAsync);

                tx.commit();
            }
        }
    }
}
 
Example 7
Source File: MvccRepeatableReadBulkOpsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Checks SQL and CacheAPI operation see consistent results before and after update.
 *
 * @throws Exception If failed.
 */
private void checkOperationsConsistency(WriteMode writeMode, boolean requestFromClient) throws Exception {
    Ignite node = grid(requestFromClient ? nodesCount() - 1 : 0);

    TestCache<Integer, MvccTestAccount> cache = new TestCache<>(node.cache(DEFAULT_CACHE_NAME));

    final Set<Integer> keysForUpdate = new HashSet<>(3);
    final Set<Integer> keysForRemove = new HashSet<>(3);

    final Set<Integer> allKeys = generateKeySet(grid(0).cache(DEFAULT_CACHE_NAME), keysForUpdate, keysForRemove);

    try {
        int updCnt = 1;

        final Map<Integer, MvccTestAccount> initialVals = allKeys.stream().collect(
            Collectors.toMap(k -> k, k -> new MvccTestAccount(k, 1)));

        updateEntries(cache, initialVals, writeMode);

        assertEquals(initialVals.size(), cache.cache.size());

        IgniteTransactions txs = node.transactions();

        Map<Integer, MvccTestAccount> updatedVals = null;

        try (Transaction tx = txs.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.REPEATABLE_READ)) {
            Map<Integer, MvccTestAccount> vals1 = getEntries(cache, allKeys, GET);
            Map<Integer, MvccTestAccount> vals2 = getEntries(cache, allKeys, SQL);
            Map<Integer, MvccTestAccount> vals3 = getEntries(cache, allKeys, ReadMode.INVOKE);

            assertEquals(initialVals, vals1);
            assertEquals(initialVals, vals2);
            assertEquals(initialVals, vals3);

            assertEquals(initialVals.size(), cache.cache.size());

            for (ReadMode readMode : new ReadMode[] {GET, SQL, INVOKE}) {
                int updCnt0 = ++updCnt;

                updatedVals = allKeys.stream().collect(Collectors.toMap(Function.identity(),
                    k -> new MvccTestAccount(k, updCnt0)));

                updateEntries(cache, updatedVals, writeMode);
                assertEquals(allKeys.size(), cache.cache.size());

                removeEntries(cache, keysForRemove, writeMode);

                for (Integer key : keysForRemove)
                    updatedVals.remove(key);

                assertEquals(String.valueOf(readMode), updatedVals, getEntries(cache, allKeys, readMode));
            }

            tx.commit();
        }

        try (Transaction tx = txs.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.REPEATABLE_READ)) {
            assertEquals(updatedVals, getEntries(cache, allKeys, GET));
            assertEquals(updatedVals, getEntries(cache, allKeys, SQL));
            assertEquals(updatedVals, getEntries(cache, allKeys, INVOKE));

            tx.commit();
        }

        assertEquals(updatedVals.size(), cache.cache.size());
    }
    finally {
        cache.cache.removeAll(keysForUpdate);
    }

    assertEquals(0, cache.cache.size());
}
 
Example 8
Source File: MvccRepeatableReadOperationsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Check getAndPut/getAndRemove operations consistency.
 *
 * @throws IgniteCheckedException If failed.
 */
@Test
public void testReplaceConsistency() throws IgniteCheckedException {
    Ignite node1 = grid(0);

    TestCache<Integer, MvccTestAccount> cache1 = new TestCache<>(node1.cache(DEFAULT_CACHE_NAME));

    final Set<Integer> existedKeys = new HashSet<>(3);
    final Set<Integer> nonExistedKeys = new HashSet<>(3);

    final Set<Integer> allKeys = generateKeySet(grid(0).cache(DEFAULT_CACHE_NAME), existedKeys, nonExistedKeys);

    final Map<Integer, MvccTestAccount> initialMap = existedKeys.stream().collect(
        Collectors.toMap(k -> k, k -> new MvccTestAccount(k, 1)));

    Map<Integer, MvccTestAccount> updateMap = existedKeys.stream().collect(
        Collectors.toMap(k -> k, k -> new MvccTestAccount(k, 3)));

    cache1.cache.putAll(initialMap);

    IgniteTransactions txs = node1.transactions();
    try (Transaction tx = txs.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.REPEATABLE_READ)) {
        for (Integer key : allKeys) {
            MvccTestAccount newVal = new MvccTestAccount(key, 2);

            if (existedKeys.contains(key)) {
                assertTrue(cache1.cache.replace(key, new MvccTestAccount(key, 1), newVal));

                assertEquals(newVal, cache1.cache.getAndReplace(key, new MvccTestAccount(key, 3)));
            }
            else {
                assertFalse(cache1.cache.replace(key, new MvccTestAccount(key, 1), newVal));

                assertNull(cache1.cache.getAndReplace(key, new MvccTestAccount(key, 3)));
            }
        }

        assertEquals(updateMap, getEntries(cache1, allKeys, SQL));
        assertEquals(updateMap, getEntries(cache1, allKeys, GET));

        tx.commit();
    }

    assertEquals(updateMap, getEntries(cache1, allKeys, SQL));
    assertEquals(updateMap, getEntries(cache1, allKeys, GET));
}
 
Example 9
Source File: CacheMvccTransactionsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testRebalanceWithRemovedValuesSimple() throws Exception {
    Ignite node = startGrid(0);

    IgniteTransactions txs = node.transactions();

    final IgniteCache<Object, Object> cache = node.createCache(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, 64));

    try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int k = 0; k < 100; k++)
            cache.remove(k);

        tx.commit();
    }

    Map<Object, Object> expVals = new HashMap<>();

    try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int k = 100; k < 200; k++) {
            cache.put(k, k);

            expVals.put(k, k);
        }

        tx.commit();
    }

    try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int k = 100; k < 200; k++) {
            if (k % 2 == 0) {
                cache.remove(k);

                expVals.remove(k);
            }
        }

        tx.commit();
    }

    startGrid(1);

    awaitPartitionMapExchange();

    checkValues(expVals, jcache(1));

    stopGrid(0);

    checkValues(expVals, jcache(1));
}
 
Example 10
Source File: CacheSerializableTransactionsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testTxRollbackIfLocked1() throws Exception {
    Ignite ignite0 = ignite(0);

    IgniteTransactions txs = ignite0.transactions();

    for (CacheConfiguration<Integer, Integer> ccfg : cacheConfigurations()) {
        logCacheInfo(ccfg);

        try {
            IgniteCache<Integer, Integer> cache = ignite0.createCache(ccfg);

            List<Integer> keys = testKeys(cache);

            for (Integer key : keys) {
                log.info("Test key: " + key);

                CountDownLatch latch = new CountDownLatch(1);

                IgniteInternalFuture<?> fut = lockKey(latch, cache, key);

                try {
                    try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                        cache.put(key, 2);

                        log.info("Commit");

                        tx.commit();
                    }

                    fail();
                }
                catch (TransactionOptimisticException e) {
                    log.info("Expected exception: " + e);
                }

                latch.countDown();

                fut.get();

                checkValue(key, 1, cache.getName());

                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    cache.put(key, 2);

                    tx.commit();
                }

                checkValue(key, 2, cache.getName());
            }
        }
        finally {
            destroyCache(ccfg.getName());
        }
    }
}
 
Example 11
Source File: CacheSerializableTransactionsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param locKey If {@code true} gets lock for local key.
 * @throws Exception If failed.
 */
private void rollbackIfLockedPartialLock(boolean locKey) throws Exception {
    Ignite ignite0 = ignite(0);

    final IgniteTransactions txs = ignite0.transactions();

    for (CacheConfiguration<Integer, Integer> ccfg : cacheConfigurations()) {
        logCacheInfo(ccfg);

        try {
            IgniteCache<Integer, Integer> cache = ignite0.createCache(ccfg);

            final Integer key1 = primaryKey(ignite(1).cache(cache.getName()));
            final Integer key2 = locKey ? primaryKey(cache) : primaryKey(ignite(2).cache(cache.getName()));

            CountDownLatch latch = new CountDownLatch(1);

            IgniteInternalFuture<?> fut = lockKey(latch, cache, key1);

            try {
                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    cache.put(key1, 2);
                    cache.put(key2, 2);

                    tx.commit();
                }

                fail();
            }
            catch (TransactionOptimisticException e) {
                log.info("Expected exception: " + e);
            }

            latch.countDown();

            fut.get();

            checkValue(key1, 1, cache.getName());
            checkValue(key2, null, cache.getName());

            try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                cache.put(key1, 2);
                cache.put(key2, 2);

                tx.commit();
            }

            checkValue(key1, 2, cache.getName());
            checkValue(key2, 2, cache.getName());
        }
        finally {
            destroyCache(ccfg.getName());
        }
    }
}
 
Example 12
Source File: TxDataConsistencyOnCommitFailureTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @param factory Factory.
 */
private void doTestCommitError(Supplier<Ignite> factory) throws Exception {
    Ignite crd = startGridsMultiThreaded(nodesCnt);

    crd.cache(DEFAULT_CACHE_NAME).put(KEY, KEY);

    Ignite ignite = factory.get();

    if (ignite == null)
        ignite = startClientGrid(CLIENT);

    assertNotNull(ignite.cache(DEFAULT_CACHE_NAME));

    injectMockedTxManager(ignite);

    checkKey();

    IgniteTransactions transactions = ignite.transactions();

    try (Transaction tx = transactions.txStart(TransactionConcurrency.PESSIMISTIC, TransactionIsolation.REPEATABLE_READ, 0, 1)) {
        assertNotNull(transactions.tx());

        ignite.cache(DEFAULT_CACHE_NAME).put(KEY, KEY + 1);

        tx.commit();

        fail();
    }
    catch (Exception t) {
        // No-op.
    }

    checkKey();

    checkFutures();
}