Search in sources :

Example 26 with AtomicReferenceArray

use of java.util.concurrent.atomic.AtomicReferenceArray in project ignite by apache.

the class IgniteCachePutRetryTransactionalSelfTest method explicitTransactionRetries.

/**
 * @param evict If {@code true} uses cache with eviction policy.
 * @param store If {@code true} uses cache with store.
 * @throws Exception If failed.
 */
@SuppressWarnings("unchecked")
public void explicitTransactionRetries(boolean evict, boolean store) throws Exception {
    ignite(0).createCache(cacheConfiguration(evict, store));
    final AtomicInteger idx = new AtomicInteger();
    int threads = 8;
    final AtomicReferenceArray<Exception> err = new AtomicReferenceArray<>(threads);
    IgniteInternalFuture<Long> fut = runMultiThreadedAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            int th = idx.getAndIncrement();
            int base = th * FACTOR;
            Ignite ignite = ignite(0);
            final IgniteCache<Object, Object> cache = ignite.cache(DEFAULT_CACHE_NAME);
            try {
                for (int i = 0; i < FACTOR; i++) {
                    doInTransaction(ignite, new ProcessCallable(cache, base, i));
                    if (i > 0 && i % 500 == 0)
                        info("Done: " + i);
                }
            } catch (Exception e) {
                err.set(th, e);
            }
            return null;
        }
    }, threads, "tx-runner");
    while (!fut.isDone()) {
        // Random in [2, 3].
        int stopIdx = ThreadLocalRandom.current().nextInt(2, 4);
        stopGrid(stopIdx);
        U.sleep(500);
        startGrid(stopIdx);
    }
    for (int i = 0; i < threads; i++) {
        Exception error = err.get(i);
        if (error != null)
            throw error;
    }
    // Verify contents of the cache.
    for (int g = 0; g < GRID_CNT; g++) {
        IgniteCache<Object, Object> cache = ignite(g).cache(DEFAULT_CACHE_NAME);
        for (int th = 0; th < threads; th++) {
            int base = th * FACTOR;
            String key = "key-" + base;
            Set<String> set = (Set<String>) cache.get(key);
            assertNotNull("Missing set for key: " + key, set);
            assertEquals(FACTOR, set.size());
            for (int i = 0; i < FACTOR; i++) {
                assertEquals("value-" + i, cache.get("key-" + base + "-" + i));
                assertTrue(set.contains("value-" + i));
            }
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) IgniteCache(org.apache.ignite.IgniteCache) EntryProcessorException(javax.cache.processor.EntryProcessorException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) IgniteAtomicLong(org.apache.ignite.IgniteAtomicLong) Ignite(org.apache.ignite.Ignite)

Example 27 with AtomicReferenceArray

use of java.util.concurrent.atomic.AtomicReferenceArray in project ignite by apache.

the class IgniteAtomicLongChangingTopologySelfTest method testQueueClose.

/**
 * @throws Exception If failed.
 */
public void testQueueClose() throws Exception {
    startGrids(GRID_CNT);
    int threads = 4;
    final AtomicBoolean run = new AtomicBoolean(true);
    final AtomicInteger idx = new AtomicInteger();
    final AtomicReferenceArray<Exception> arr = new AtomicReferenceArray<>(threads);
    IgniteInternalFuture<Long> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

        /**
         * {@inheritDoc}
         */
        @Override
        public Void call() throws Exception {
            int base = idx.getAndIncrement();
            try {
                int delta = 0;
                while (run.get()) {
                    IgniteAtomicLong cntr = ignite(0).atomicLong(ATOMIC_LONG_NAME + "-" + base + "-" + delta, 0, true);
                    for (int i = 0; i < 5; i++) queue.add(cntr.getAndIncrement());
                    cntr.close();
                    delta++;
                }
            } catch (Exception e) {
                arr.set(base, e);
                throw e;
            } finally {
                info("RUNNER THREAD IS STOPPING");
            }
            return null;
        }
    }, threads, "increment-runner");
    for (int i = 0; i < RESTART_CNT; i++) {
        int restartIdx = ThreadLocalRandom.current().nextInt(GRID_CNT - 1) + 1;
        stopGrid(restartIdx);
        U.sleep(500);
        startGrid(restartIdx);
    }
    run.set(false);
    fut.get();
    for (int i = 0; i < threads; i++) {
        Exception err = arr.get(i);
        if (err != null)
            throw err;
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) IgniteAtomicLong(org.apache.ignite.IgniteAtomicLong) IgniteAtomicLong(org.apache.ignite.IgniteAtomicLong) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException)

Example 28 with AtomicReferenceArray

use of java.util.concurrent.atomic.AtomicReferenceArray in project ignite by apache.

the class WebSessionSelfTest method testRestarts.

/**
 * @throws Exception If failed.
 */
public void testRestarts() throws Exception {
    final AtomicReference<String> sesIdRef = new AtomicReference<>();
    final AtomicReferenceArray<Server> srvs = new AtomicReferenceArray<>(SRV_CNT);
    for (int idx = 0; idx < SRV_CNT; idx++) {
        String cfg = "/modules/core/src/test/config/websession/spring-cache-" + (idx + 1) + ".xml";
        srvs.set(idx, startServer(TEST_JETTY_PORT + idx, cfg, "grid-" + (idx + 1), new RestartsTestServlet(sesIdRef)));
    }
    final AtomicBoolean stop = new AtomicBoolean();
    IgniteInternalFuture<?> restarterFut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {

        @SuppressWarnings("BusyWait")
        @Override
        public Object call() throws Exception {
            Random rnd = new Random();
            for (int i = 0; i < 10; i++) {
                int idx = -1;
                Server srv = null;
                while (srv == null) {
                    idx = rnd.nextInt(SRV_CNT);
                    srv = srvs.getAndSet(idx, null);
                }
                assert idx != -1;
                stopServer(srv);
                String cfg = "/modules/core/src/test/config/websession/spring-cache-" + (idx + 1) + ".xml";
                srv = startServer(TEST_JETTY_PORT + idx, cfg, "grid-" + (idx + 1), new RestartsTestServlet(sesIdRef));
                assert srvs.compareAndSet(idx, null, srv);
                Thread.sleep(100);
            }
            X.println("Stopping...");
            stop.set(true);
            return null;
        }
    }, 1, "restarter");
    Server srv = null;
    try {
        Random rnd = new Random();
        int n = 0;
        while (!stop.get()) {
            int idx = -1;
            while (srv == null) {
                idx = rnd.nextInt(SRV_CNT);
                srv = srvs.getAndSet(idx, null);
            }
            assert idx != -1;
            int port = TEST_JETTY_PORT + idx;
            URLConnection conn = new URL("http://localhost:" + port + "/ignitetest/test").openConnection();
            String sesId = sesIdRef.get();
            if (sesId != null)
                conn.addRequestProperty("Cookie", "JSESSIONID=" + sesId);
            conn.connect();
            String str;
            try (BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                str = rdr.readLine();
            }
            assertEquals(n, Integer.parseInt(str));
            n++;
            assert srvs.compareAndSet(idx, null, srv);
            srv = null;
        }
        X.println(">>> Made " + n + " requests.");
    } finally {
        restarterFut.get();
        if (srv != null)
            stopServer(srv);
        for (int i = 0; i < srvs.length(); i++) stopServer(srvs.get(i));
    }
}
Also used : Server(org.eclipse.jetty.server.Server) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServletException(javax.servlet.ServletException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URL(java.net.URL) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray)

Example 29 with AtomicReferenceArray

use of java.util.concurrent.atomic.AtomicReferenceArray in project gocd by gocd.

the class ConcurrentHashMapV8 method internalComputeIfAbsent.

/**
 * Implementation for computeIfAbsent
 */
private final Object internalComputeIfAbsent(K k, Fun<? super K, ?> mf) {
    int h = spread(k.hashCode());
    Object val = null;
    int count = 0;
    for (AtomicReferenceArray<Node> tab = table; ; ) {
        Node f;
        int i, fh;
        Object fk, fv;
        if (tab == null)
            tab = initTable();
        else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) {
            Node node = new Node(fh = h | LOCKED, k, null, null);
            if (casTabAt(tab, i, null, node)) {
                count = 1;
                try {
                    if ((val = mf.apply(k)) != null)
                        node.val = val;
                } finally {
                    if (val == null)
                        setTabAt(tab, i, null);
                    if (!node.casHash(fh, h)) {
                        node.hash = h;
                        synchronized (node) {
                            node.notifyAll();
                        }
                        ;
                    }
                }
            }
            if (count != 0)
                break;
        } else if ((fh = f.hash) == MOVED) {
            if ((fk = f.key) instanceof TreeBin) {
                TreeBin t = (TreeBin) fk;
                boolean added = false;
                t.acquire(0);
                try {
                    if (tabAt(tab, i) == f) {
                        count = 1;
                        TreeNode p = t.getTreeNode(h, k, t.root);
                        if (p != null)
                            val = p.val;
                        else if ((val = mf.apply(k)) != null) {
                            added = true;
                            count = 2;
                            t.putTreeNode(h, k, val);
                        }
                    }
                } finally {
                    t.release(0);
                }
                if (count != 0) {
                    if (!added)
                        return val;
                    break;
                }
            } else
                tab = (AtomicReferenceArray<Node>) fk;
        } else if ((fh & HASH_BITS) == h && (fv = f.val) != null && ((fk = f.key) == k || k.equals(fk)))
            return fv;
        else {
            Node g = f.next;
            if (g != null) {
                for (Node e = g; ; ) {
                    Object ek, ev;
                    if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && ((ek = e.key) == k || k.equals(ek)))
                        return ev;
                    if ((e = e.next) == null) {
                        checkForResize();
                        break;
                    }
                }
            }
            if (((fh = f.hash) & LOCKED) != 0) {
                checkForResize();
                f.tryAwaitLock(tab, i);
            } else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
                boolean added = false;
                try {
                    if (tabAt(tab, i) == f) {
                        count = 1;
                        for (Node e = f; ; ++count) {
                            Object ek, ev;
                            if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && ((ek = e.key) == k || k.equals(ek))) {
                                val = ev;
                                break;
                            }
                            Node last = e;
                            if ((e = e.next) == null) {
                                if ((val = mf.apply(k)) != null) {
                                    added = true;
                                    last.next = new Node(h, k, val, null);
                                    if (count >= TREE_THRESHOLD)
                                        replaceWithTreeBin(tab, i, k);
                                }
                                break;
                            }
                        }
                    }
                } finally {
                    if (!f.casHash(fh | LOCKED, fh)) {
                        f.hash = fh;
                        synchronized (f) {
                            f.notifyAll();
                        }
                        ;
                    }
                }
                if (count != 0) {
                    if (!added)
                        return val;
                    if (tab.length() <= 64)
                        count = 2;
                    break;
                }
            }
        }
    }
    if (val != null) {
        counter.add(1L);
        if (count > 1)
            checkForResize();
    }
    return val;
}
Also used : AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) RubyObject(org.jruby.RubyObject) IRubyObject(org.jruby.runtime.builtin.IRubyObject)

Example 30 with AtomicReferenceArray

use of java.util.concurrent.atomic.AtomicReferenceArray in project gocd by gocd.

the class ConcurrentHashMapV8 method internalPutAll.

/**
 * Implementation for putAll
 */
private final void internalPutAll(Map<?, ?> m) {
    tryPresize(m.size());
    // number of uncommitted additions
    long delta = 0L;
    // to throw exception on exit for nulls
    boolean npe = false;
    try {
        // to clean up counts on other exceptions
        for (Map.Entry<?, ?> entry : m.entrySet()) {
            Object k, v;
            if (entry == null || (k = entry.getKey()) == null || (v = entry.getValue()) == null) {
                npe = true;
                break;
            }
            int h = spread(k.hashCode());
            for (AtomicReferenceArray<Node> tab = table; ; ) {
                int i;
                Node f;
                int fh;
                Object fk;
                if (tab == null)
                    tab = initTable();
                else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) {
                    if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
                        ++delta;
                        break;
                    }
                } else if ((fh = f.hash) == MOVED) {
                    if ((fk = f.key) instanceof TreeBin) {
                        TreeBin t = (TreeBin) fk;
                        boolean validated = false;
                        t.acquire(0);
                        try {
                            if (tabAt(tab, i) == f) {
                                validated = true;
                                TreeNode p = t.getTreeNode(h, k, t.root);
                                if (p != null)
                                    p.val = v;
                                else {
                                    t.putTreeNode(h, k, v);
                                    ++delta;
                                }
                            }
                        } finally {
                            t.release(0);
                        }
                        if (validated)
                            break;
                    } else
                        tab = (AtomicReferenceArray<Node>) fk;
                } else if ((fh & LOCKED) != 0) {
                    counter.add(delta);
                    delta = 0L;
                    checkForResize();
                    f.tryAwaitLock(tab, i);
                } else if (f.casHash(fh, fh | LOCKED)) {
                    int count = 0;
                    try {
                        if (tabAt(tab, i) == f) {
                            count = 1;
                            for (Node e = f; ; ++count) {
                                Object ek, ev;
                                if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && ((ek = e.key) == k || k.equals(ek))) {
                                    e.val = v;
                                    break;
                                }
                                Node last = e;
                                if ((e = e.next) == null) {
                                    ++delta;
                                    last.next = new Node(h, k, v, null);
                                    if (count >= TREE_THRESHOLD)
                                        replaceWithTreeBin(tab, i, k);
                                    break;
                                }
                            }
                        }
                    } finally {
                        if (!f.casHash(fh | LOCKED, fh)) {
                            f.hash = fh;
                            synchronized (f) {
                                f.notifyAll();
                            }
                            ;
                        }
                    }
                    if (count != 0) {
                        if (count > 1) {
                            counter.add(delta);
                            delta = 0L;
                            checkForResize();
                        }
                        break;
                    }
                }
            }
        }
    } finally {
        if (delta != 0)
            counter.add(delta);
    }
    if (npe)
        throw new NullPointerException();
}
Also used : AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) RubyObject(org.jruby.RubyObject) IRubyObject(org.jruby.runtime.builtin.IRubyObject) ConcurrentHashMap(org.jruby.ext.thread_safe.jsr166e.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Aggregations

AtomicReferenceArray (java.util.concurrent.atomic.AtomicReferenceArray)32 CountDownLatch (java.util.concurrent.CountDownLatch)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 RubyObject (org.jruby.RubyObject)6 IRubyObject (org.jruby.runtime.builtin.IRubyObject)6 Config (com.hazelcast.config.Config)4 HazelcastInstance (com.hazelcast.core.HazelcastInstance)4 Random (java.util.Random)4 Test (org.junit.Test)4 Thread.currentThread (java.lang.Thread.currentThread)3 ExecutorService (java.util.concurrent.ExecutorService)3 Ignite (org.apache.ignite.Ignite)3 IgniteCache (org.apache.ignite.IgniteCache)3 JoinConfig (com.hazelcast.config.JoinConfig)2 MulticastConfig (com.hazelcast.config.MulticastConfig)2 NetworkConfig (com.hazelcast.config.NetworkConfig)2 TcpIpConfig (com.hazelcast.config.TcpIpConfig)2 IMap (com.hazelcast.core.IMap)2 TestHazelcastInstanceFactory (com.hazelcast.test.TestHazelcastInstanceFactory)2