Search in sources :

Example 31 with TransactionOptimisticException

use of org.apache.ignite.transactions.TransactionOptimisticException in project ignite by apache.

the class CacheSerializableTransactionsTest method testConflictResolution.

/**
 * @throws Exception If failed.
 */
public void testConflictResolution() throws Exception {
    final Ignite ignite = ignite(0);
    final String cacheName = ignite.createCache(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, false, false)).getName();
    try {
        final Map<Integer, Integer> keys = new HashMap<>();
        for (int i = 0; i < 500; i++) keys.put(i, i);
        final int THREADS = 5;
        for (int i = 0; i < 10; i++) {
            final CyclicBarrier barrier = new CyclicBarrier(THREADS);
            final AtomicInteger commitCntr = new AtomicInteger(0);
            GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    IgniteCache<Integer, Integer> cache = ignite.cache(cacheName);
                    IgniteTransactions txs = cache.unwrap(Ignite.class).transactions();
                    try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                        cache.putAll(keys);
                        barrier.await();
                        tx.commit();
                        commitCntr.incrementAndGet();
                    } catch (TransactionOptimisticException e) {
                        log.info("Optimistic error: " + e);
                    }
                    return null;
                }
            }, THREADS, "update-thread").get();
            int commits = commitCntr.get();
            log.info("Iteration [iter=" + i + ", commits=" + commits + ']');
            assertTrue(commits > 0);
        }
    } finally {
        destroyCache(cacheName);
    }
}
Also used : TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IgniteTransactions(org.apache.ignite.IgniteTransactions) Callable(java.util.concurrent.Callable) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Ignite(org.apache.ignite.Ignite)

Example 32 with TransactionOptimisticException

use of org.apache.ignite.transactions.TransactionOptimisticException in project ignite by apache.

the class CacheSerializableTransactionsTest method testReadWriteTxConflict.

/**
 * @throws Exception If failed.
 */
@SuppressWarnings("UnnecessaryLocalVariable")
public void testReadWriteTxConflict() throws Exception {
    Ignite ignite0 = ignite(0);
    for (CacheConfiguration<Integer, Integer> ccfg : cacheConfigurations()) {
        logCacheInfo(ccfg);
        ignite0.createCache(ccfg);
        try {
            Ignite ignite = ignite0;
            IgniteCache<Integer, Integer> cache = ignite.cache(ccfg.getName());
            Integer writeKey = Integer.MAX_VALUE;
            List<Integer> readKeys = testKeys(cache);
            for (Integer readKey : readKeys) {
                try {
                    // No conflict for read, conflict for write.
                    try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, SERIALIZABLE)) {
                        cache.getAndPut(writeKey, writeKey);
                        cache.get(readKey);
                        updateKey(cache, writeKey, writeKey + readKey);
                        tx.commit();
                    }
                    fail();
                } catch (TransactionOptimisticException e) {
                    log.info("Expected exception: " + e);
                }
                assertEquals((Integer) (writeKey + readKey), cache.get(writeKey));
                assertNull(cache.get(readKey));
                cache.put(readKey, readKey);
                assertEquals(readKey, cache.get(readKey));
            }
        } finally {
            destroyCache(ccfg.getName());
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) Transaction(org.apache.ignite.transactions.Transaction) Ignite(org.apache.ignite.Ignite)

Example 33 with TransactionOptimisticException

use of org.apache.ignite.transactions.TransactionOptimisticException in project ignite by apache.

the class CacheSerializableTransactionsTest method txConflictRemoveReturnBoolean.

/**
 * @param noVal If {@code true} there is no cache value when do update in tx.
 * @throws Exception If failed.
 */
private void txConflictRemoveReturnBoolean(boolean noVal) 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);
            List<Integer> keys = testKeys(cache);
            for (final Integer key : keys) {
                log.info("Test key: " + key);
                if (!noVal)
                    cache.put(key, -1);
                if (noVal) {
                    try {
                        try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                            boolean res = cache.remove(key);
                            assertFalse(res);
                            updateKey(cache, key, -1);
                            tx.commit();
                        }
                        fail();
                    } catch (TransactionOptimisticException e) {
                        log.info("Expected exception: " + e);
                    }
                    checkValue(key, -1, cache.getName());
                } else {
                    try {
                        try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                            boolean res = cache.remove(key);
                            assertTrue(res);
                            txAsync(cache, PESSIMISTIC, REPEATABLE_READ, new IgniteClosure<IgniteCache<Integer, Integer>, Void>() {

                                @Override
                                public Void apply(IgniteCache<Integer, Integer> cache) {
                                    cache.remove(key);
                                    return null;
                                }
                            });
                            tx.commit();
                        }
                        fail();
                    } catch (TransactionOptimisticException e) {
                        log.info("Expected exception: " + e);
                    }
                    checkValue(key, null, cache.getName());
                    cache.put(key, -1);
                }
                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    boolean res = cache.remove(key);
                    assertTrue(res);
                    updateKey(cache, key, 2);
                    tx.commit();
                }
                checkValue(key, null, cache.getName());
                // Check no conflict for removeAll with single key.
                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    cache.removeAll(Collections.singleton(key));
                    txAsync(cache, PESSIMISTIC, REPEATABLE_READ, new IgniteClosure<IgniteCache<Integer, Integer>, Void>() {

                        @Override
                        public Void apply(IgniteCache<Integer, Integer> cache) {
                            cache.remove(key);
                            return null;
                        }
                    });
                    tx.commit();
                }
                checkValue(key, null, cache.getName());
                cache.put(key, 2);
                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    boolean res = cache.remove(key);
                    assertTrue(res);
                    tx.commit();
                }
                checkValue(key, null, cache.getName());
                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                    boolean res = cache.remove(key);
                    assertFalse(res);
                    tx.commit();
                }
                checkValue(key, null, cache.getName());
                try {
                    cache.put(key, 1);
                    try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                        Object val = cache.get(key);
                        assertEquals(1, val);
                        boolean res = cache.remove(key);
                        assertTrue(res);
                        updateKey(cache, key, 2);
                        tx.commit();
                    }
                    fail();
                } catch (TransactionOptimisticException e) {
                    log.info("Expected exception: " + e);
                }
            }
        } finally {
            destroyCache(ccfg.getName());
        }
    }
}
Also used : TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) IgniteCache(org.apache.ignite.IgniteCache) IgniteTransactions(org.apache.ignite.IgniteTransactions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Transaction(org.apache.ignite.transactions.Transaction) Ignite(org.apache.ignite.Ignite)

Example 34 with TransactionOptimisticException

use of org.apache.ignite.transactions.TransactionOptimisticException in project ignite by apache.

the class CacheSerializableTransactionsTest method getRemoveTx.

/**
 * @param nearCache If {@code true} near cache is enabled.
 * @param store If {@code true} cache store is enabled.
 * @throws Exception If failed.
 */
private void getRemoveTx(boolean nearCache, boolean store) throws Exception {
    long stopTime = U.currentTimeMillis() + getTestTimeout() - 30_000;
    final Ignite ignite0 = ignite(0);
    CacheConfiguration<Integer, Integer> ccfg = cacheConfiguration(PARTITIONED, FULL_SYNC, 0, store, false);
    final List<Ignite> clients = clients();
    final String cacheName = ignite0.createCache(ccfg).getName();
    try {
        final List<IgniteCache<Integer, Integer>> caches = new ArrayList<>();
        for (Ignite client : clients) {
            if (nearCache)
                caches.add(client.createNearCache(cacheName, new NearCacheConfiguration<Integer, Integer>()));
            else
                caches.add(client.<Integer, Integer>cache(cacheName));
        }
        for (int i = 0; i < 100; i++) {
            if (U.currentTimeMillis() > stopTime)
                break;
            final AtomicInteger cntr = new AtomicInteger();
            final Integer key = i;
            final AtomicInteger threadIdx = new AtomicInteger();
            final int THREADS = 10;
            final CyclicBarrier barrier = new CyclicBarrier(THREADS);
            final IgniteInternalFuture<?> updateFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    int thread = threadIdx.getAndIncrement();
                    int idx = thread % caches.size();
                    IgniteCache<Integer, Integer> cache = caches.get(idx);
                    Ignite ignite = cache.unwrap(Ignite.class);
                    IgniteTransactions txs = ignite.transactions();
                    log.info("Started update thread: " + ignite.name());
                    Thread.currentThread().setName("update-thread-" + ignite.name() + "-" + thread);
                    barrier.await();
                    for (int i = 0; i < 50; i++) {
                        while (true) {
                            try {
                                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                                boolean rmv = rnd.nextInt(3) == 0;
                                Integer val;
                                try (Transaction tx = txs.txStart(OPTIMISTIC, SERIALIZABLE)) {
                                    val = cache.get(key);
                                    if (rmv)
                                        cache.remove(key);
                                    else
                                        cache.put(key, val == null ? 1 : val + 1);
                                    tx.commit();
                                    if (rmv) {
                                        if (val != null) {
                                            for (int j = 0; j < val; j++) cntr.decrementAndGet();
                                        }
                                    } else
                                        cntr.incrementAndGet();
                                }
                                break;
                            } catch (TransactionOptimisticException ignore) {
                            // Retry.
                            }
                        }
                    }
                    return null;
                }
            }, THREADS, "update-thread");
            updateFut.get();
            Integer val = cntr.get();
            log.info("Iteration [iter=" + i + ", val=" + val + ']');
            checkValue(key, val == 0 ? null : val, cacheName);
        }
    } finally {
        destroyCache(cacheName);
    }
}
Also used : TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) IgniteCache(org.apache.ignite.IgniteCache) ArrayList(java.util.ArrayList) IgniteTransactions(org.apache.ignite.IgniteTransactions) TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) IgniteException(org.apache.ignite.IgniteException) CacheLoaderException(javax.cache.integration.CacheLoaderException) CacheException(javax.cache.CacheException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Ignite(org.apache.ignite.Ignite)

Example 35 with TransactionOptimisticException

use of org.apache.ignite.transactions.TransactionOptimisticException in project ignite by apache.

the class IgniteTxCacheWriteSynchronizationModesMultithreadedTest method multithreaded.

/**
 * @param syncMode Write synchronization mode.
 * @param backups Number of backups.
 * @param store If {@code true} sets store in cache configuration.
 * @param nearCache If {@code true} creates near cache on one of client nodes.
 * @param restart If {@code true} restarts one node during test.
 * @throws Exception If failed.
 */
private void multithreaded(CacheWriteSynchronizationMode syncMode, int backups, boolean store, boolean nearCache, boolean restart) throws Exception {
    final Ignite ignite = ignite(0);
    createCache(ignite, cacheConfiguration(DEFAULT_CACHE_NAME, syncMode, backups, store), nearCache);
    final AtomicBoolean stop = new AtomicBoolean();
    IgniteInternalFuture<?> restartFut = null;
    try {
        if (restart) {
            restartFut = GridTestUtils.runAsync(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    while (!stop.get()) {
                        startGrid(NODES);
                        U.sleep(100);
                        stopGrid(NODES);
                    }
                    return null;
                }
            }, "restart-thread");
        }
        commitMultithreaded(new IgniteBiInClosure<Ignite, IgniteCache<Integer, Integer>>() {

            @Override
            public void apply(Ignite ignite, IgniteCache<Integer, Integer> cache) {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                Integer key = rnd.nextInt(MULTITHREADED_TEST_KEYS);
                cache.put(key, rnd.nextInt());
            }
        });
        commitMultithreaded(new IgniteBiInClosure<Ignite, IgniteCache<Integer, Integer>>() {

            @Override
            public void apply(Ignite ignite, IgniteCache<Integer, Integer> cache) {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                Map<Integer, Integer> map = new TreeMap<>();
                for (int i = 0; i < 100; i++) {
                    Integer key = rnd.nextInt(MULTITHREADED_TEST_KEYS);
                    map.put(key, rnd.nextInt());
                }
                cache.putAll(map);
            }
        });
        commitMultithreaded(new IgniteBiInClosure<Ignite, IgniteCache<Integer, Integer>>() {

            @Override
            public void apply(Ignite ignite, IgniteCache<Integer, Integer> cache) {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                Map<Integer, Integer> map = new TreeMap<>();
                for (int i = 0; i < 100; i++) {
                    Integer key = rnd.nextInt(MULTITHREADED_TEST_KEYS);
                    map.put(key, rnd.nextInt());
                }
                try {
                    try (Transaction tx = ignite.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                        for (Map.Entry<Integer, Integer> e : map.entrySet()) cache.put(e.getKey(), e.getValue());
                        tx.commit();
                    }
                } catch (CacheException | IgniteException ignored) {
                // No-op.
                }
            }
        });
        commitMultithreaded(new IgniteBiInClosure<Ignite, IgniteCache<Integer, Integer>>() {

            @Override
            public void apply(Ignite ignite, IgniteCache<Integer, Integer> cache) {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                Map<Integer, Integer> map = new LinkedHashMap<>();
                for (int i = 0; i < 10; i++) {
                    Integer key = rnd.nextInt(MULTITHREADED_TEST_KEYS);
                    map.put(key, rnd.nextInt());
                }
                while (true) {
                    try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, SERIALIZABLE)) {
                        for (Map.Entry<Integer, Integer> e : map.entrySet()) cache.put(e.getKey(), e.getValue());
                        tx.commit();
                        break;
                    } catch (TransactionOptimisticException ignored) {
                    // Retry.
                    } catch (CacheException | IgniteException ignored) {
                        break;
                    }
                }
            }
        });
    } finally {
        stop.set(true);
        ignite.destroyCache(DEFAULT_CACHE_NAME);
        if (restartFut != null)
            restartFut.get();
    }
}
Also used : TransactionOptimisticException(org.apache.ignite.transactions.TransactionOptimisticException) IgniteCache(org.apache.ignite.IgniteCache) Callable(java.util.concurrent.Callable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Transaction(org.apache.ignite.transactions.Transaction) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Ignite(org.apache.ignite.Ignite) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Aggregations

TransactionOptimisticException (org.apache.ignite.transactions.TransactionOptimisticException)39 Transaction (org.apache.ignite.transactions.Transaction)38 Ignite (org.apache.ignite.Ignite)33 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)32 IgniteTransactions (org.apache.ignite.IgniteTransactions)27 IgniteCache (org.apache.ignite.IgniteCache)14 IgniteException (org.apache.ignite.IgniteException)10 CacheException (javax.cache.CacheException)9 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)9 Callable (java.util.concurrent.Callable)8 HashMap (java.util.HashMap)7 LinkedHashMap (java.util.LinkedHashMap)7 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)7 CacheLoaderException (javax.cache.integration.CacheLoaderException)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 CyclicBarrier (java.util.concurrent.CyclicBarrier)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5