java.util.concurrent.atomic.AtomicIntegerArray

Here are the examples of the java api class java.util.concurrent.atomic.AtomicIntegerArray taken from open source projects.

1. AtomicIntegerArrayTest#testCompareAndSetInMultipleThreads()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * compareAndSet in one thread enables another waiting for value
     * to succeed
     */
public void testCompareAndSetInMultipleThreads() throws Exception {
    final AtomicIntegerArray a = new AtomicIntegerArray(1);
    a.set(0, 1);
    Thread t = new Thread(new CheckedRunnable() {

        public void realRun() {
            while (!a.compareAndSet(0, 2, 3)) Thread.yield();
        }
    });
    t.start();
    assertTrue(a.compareAndSet(0, 1, 2));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
    assertEquals(3, a.get(0));
}

2. AtomicIntegerArrayTest#testCompareAndSet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * compareAndSet succeeds in changing value if equal to expected else fails
     */
public void testCompareAndSet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertTrue(aa.compareAndSet(i, 1, 2));
        assertTrue(aa.compareAndSet(i, 2, -4));
        assertEquals(-4, aa.get(i));
        assertFalse(aa.compareAndSet(i, -5, 7));
        assertEquals(-4, aa.get(i));
        assertTrue(aa.compareAndSet(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}

3. Test#foo()

Project: intellij-community
Source File: Test.java
View license
void foo() {
    a.getAndIncrement(0);
    System.out.println(a.incrementAndGet(0));
    a.getAndDecrement(0);
    if (a.decrementAndGet(0) == 0) {
        a.getAndAdd(0, ((2)));
        a.set(0, a.get(0) * 2);
        if (a.get(0) == 0) {
            System.out.println(a.get(0) + 7);
        }
    }
    a = new AtomicIntegerArray(new int[0]);
}

4. AtomicIntegerArrayTest#testCountingInMultipleThreads()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * Multiple threads using same array of counters successfully
     * update a number of times equal to total count
     */
public void testCountingInMultipleThreads() throws InterruptedException {
    final AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    int countdown = 10000;
    for (int i = 0; i < SIZE; i++) aa.set(i, countdown);
    Counter c1 = new Counter(aa);
    Counter c2 = new Counter(aa);
    Thread t1 = new Thread(c1);
    Thread t2 = new Thread(c2);
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    assertEquals(c1.counts + c2.counts, SIZE * countdown);
}

5. AtomicIntegerArrayTest#testIncrementAndGet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * incrementAndGet increments and returns current value
     */
public void testIncrementAndGet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(2, aa.incrementAndGet(i));
        assertEquals(2, aa.get(i));
        aa.set(i, -2);
        assertEquals(-1, aa.incrementAndGet(i));
        assertEquals(0, aa.incrementAndGet(i));
        assertEquals(1, aa.incrementAndGet(i));
        assertEquals(1, aa.get(i));
    }
}

6. AtomicIntegerArrayTest#testGetAndIncrement()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * getAndIncrement returns previous value and increments
     */
public void testGetAndIncrement() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndIncrement(i));
        assertEquals(2, aa.get(i));
        aa.set(i, -2);
        assertEquals(-2, aa.getAndIncrement(i));
        assertEquals(-1, aa.getAndIncrement(i));
        assertEquals(0, aa.getAndIncrement(i));
        assertEquals(1, aa.get(i));
    }
}

7. Atomic8Test#testIntArrayGetAndAccumulate()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicIntegerArray getAndAccumulate returns previous value and updates
     * with supplied function.
     */
public void testIntArrayGetAndAccumulate() {
    AtomicIntegerArray a = new AtomicIntegerArray(1);
    a.set(0, 1);
    assertEquals(1, a.getAndAccumulate(0, 2, Integer::sum));
    assertEquals(3, a.getAndAccumulate(0, 3, Integer::sum));
    assertEquals(6, a.get(0));
}

8. Atomic8Test#testIntArrayAccumulateAndGet()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicIntegerArray accumulateAndGet updates with supplied function and
     * returns result.
     */
public void testIntArrayAccumulateAndGet() {
    AtomicIntegerArray a = new AtomicIntegerArray(1);
    a.set(0, 1);
    assertEquals(7, a.accumulateAndGet(0, 6, Integer::sum));
    assertEquals(10, a.accumulateAndGet(0, 3, Integer::sum));
}

9. Atomic8Test#testIntArrayUpdateAndGet()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicIntegerArray updateAndGet updates with supplied function and
     * returns result.
     */
public void testIntArrayUpdateAndGet() {
    AtomicIntegerArray a = new AtomicIntegerArray(1);
    a.set(0, 1);
    assertEquals(18, a.updateAndGet(0, Atomic8Test::addInt17));
    assertEquals(35, a.updateAndGet(0, Atomic8Test::addInt17));
    assertEquals(35, a.get(0));
}

10. Atomic8Test#testIntArrayGetAndUpdate()

Project: openjdk
Source File: Atomic8Test.java
View license
/**
     * AtomicIntegerArray getAndUpdate returns previous value and updates
     * result of supplied function
     */
public void testIntArrayGetAndUpdate() {
    AtomicIntegerArray a = new AtomicIntegerArray(1);
    a.set(0, 1);
    assertEquals(1, a.getAndUpdate(0, Atomic8Test::addInt17));
    assertEquals(18, a.getAndUpdate(0, Atomic8Test::addInt17));
    assertEquals(35, a.get(0));
}

11. AtomicIntegerArrayTest#testSerialization()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * a deserialized serialized array holds same values
     */
public void testSerialization() throws Exception {
    AtomicIntegerArray x = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) x.set(i, -i);
    AtomicIntegerArray y = serialClone(x);
    assertNotSame(x, y);
    assertEquals(x.length(), y.length());
    for (int i = 0; i < SIZE; i++) {
        assertEquals(x.get(i), y.get(i));
    }
}

12. AtomicIntegerArrayTest#testGetSet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * get returns the last value set at index
     */
public void testGetSet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.get(i));
        aa.set(i, 2);
        assertEquals(2, aa.get(i));
        aa.set(i, -3);
        assertEquals(-3, aa.get(i));
    }
}

13. AtomicIntegerArrayTest#testAddAndGet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * addAndGet adds given value to current, and returns current value
     */
public void testAddAndGet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(3, aa.addAndGet(i, 2));
        assertEquals(3, aa.get(i));
        assertEquals(-1, aa.addAndGet(i, -4));
        assertEquals(-1, aa.get(i));
    }
}

14. AtomicIntegerArrayTest#testDecrementAndGet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * decrementAndGet decrements and returns current value
     */
public void testDecrementAndGet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(0, aa.decrementAndGet(i));
        assertEquals(-1, aa.decrementAndGet(i));
        assertEquals(-2, aa.decrementAndGet(i));
        assertEquals(-2, aa.get(i));
    }
}

15. AtomicIntegerArrayTest#testGetAndDecrement()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * getAndDecrement returns previous value and decrements
     */
public void testGetAndDecrement() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndDecrement(i));
        assertEquals(0, aa.getAndDecrement(i));
        assertEquals(-1, aa.getAndDecrement(i));
    }
}

16. AtomicIntegerArrayTest#testGetAndAdd()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * getAndAdd returns previous value and adds given value
     */
public void testGetAndAdd() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndAdd(i, 2));
        assertEquals(3, aa.get(i));
        assertEquals(3, aa.getAndAdd(i, -4));
        assertEquals(-1, aa.get(i));
    }
}

17. AtomicIntegerArrayTest#testGetAndSet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * getAndSet returns previous value and sets to given value at given index
     */
public void testGetAndSet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        assertEquals(1, aa.getAndSet(i, 0));
        assertEquals(0, aa.getAndSet(i, -10));
        assertEquals(-10, aa.getAndSet(i, 1));
    }
}

18. AtomicIntegerArrayTest#testToString()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * toString returns current value.
     */
public void testToString() {
    int[] a = { 17, 3, -42, 99, -7 };
    AtomicIntegerArray aa = new AtomicIntegerArray(a);
    assertEquals(Arrays.toString(a), aa.toString());
}

19. AtomicIntegerArrayTest#testWeakCompareAndSet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * repeated weakCompareAndSet succeeds in changing value when equal
     * to expected
     */
public void testWeakCompareAndSet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.set(i, 1);
        do {
        } while (!aa.weakCompareAndSet(i, 1, 2));
        do {
        } while (!aa.weakCompareAndSet(i, 2, -4));
        assertEquals(-4, aa.get(i));
        do {
        } while (!aa.weakCompareAndSet(i, -4, 7));
        assertEquals(7, aa.get(i));
    }
}

20. AtomicIntegerArrayTest#testGetLazySet()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * get returns the last value lazySet at index by same thread
     */
public void testGetLazySet() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) {
        aa.lazySet(i, 1);
        assertEquals(1, aa.get(i));
        aa.lazySet(i, 2);
        assertEquals(2, aa.get(i));
        aa.lazySet(i, -3);
        assertEquals(-3, aa.get(i));
    }
}

21. IndexActionIT#testCreatedFlagParallelExecution()

Project: elasticsearch
Source File: IndexActionIT.java
View license
public void testCreatedFlagParallelExecution() throws Exception {
    createIndex("test");
    ensureGreen();
    int threadCount = 20;
    final int docCount = 300;
    int taskCount = docCount * threadCount;
    final AtomicIntegerArray createdCounts = new AtomicIntegerArray(docCount);
    ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
    List<Callable<Void>> tasks = new ArrayList<>(taskCount);
    final Random random = random();
    for (int i = 0; i < taskCount; i++) {
        tasks.add(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                int docId = random.nextInt(docCount);
                IndexResponse indexResponse = index("test", "type", Integer.toString(docId), "field1", "value");
                if (indexResponse.isCreated())
                    createdCounts.incrementAndGet(docId);
                return null;
            }
        });
    }
    threadPool.invokeAll(tasks);
    for (int i = 0; i < docCount; i++) {
        assertThat(createdCounts.get(i), lessThanOrEqualTo(1));
    }
    terminate(threadPool);
}

22. AtomicIntegerArrayTest#testIndexing()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * get and set for out of bound indices throw IndexOutOfBoundsException
     */
public void testIndexing() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int index : new int[] { -1, SIZE }) {
        try {
            aa.get(index);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.set(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.lazySet(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.compareAndSet(index, 1, 2);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.weakCompareAndSet(index, 1, 2);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.getAndAdd(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
        try {
            aa.addAndGet(index, 1);
            shouldThrow();
        } catch (IndexOutOfBoundsException success) {
        }
    }
}

23. AtomicIntegerArrayTest#testConstructor2()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * constructor with array is of same size and has all elements
     */
public void testConstructor2() {
    int[] a = { 17, 3, -42, 99, -7 };
    AtomicIntegerArray aa = new AtomicIntegerArray(a);
    assertEquals(a.length, aa.length());
    for (int i = 0; i < a.length; i++) assertEquals(a[i], aa.get(i));
}

24. AtomicIntegerArrayTest#testConstructor()

Project: openjdk
Source File: AtomicIntegerArrayTest.java
View license
/**
     * constructor creates array of given size with all elements zero
     */
public void testConstructor() {
    AtomicIntegerArray aa = new AtomicIntegerArray(SIZE);
    for (int i = 0; i < SIZE; i++) assertEquals(0, aa.get(i));
}

25. Lazy#main()

Project: openjdk
Source File: Lazy.java
View license
public static void main(String[] args) throws Exception {
    final AtomicBoolean b = new AtomicBoolean();
    final AtomicInteger i = new AtomicInteger();
    final AtomicLong l = new AtomicLong();
    final AtomicReference<Long> r = new AtomicReference<Long>();
    final AtomicIntegerArray ia = new AtomicIntegerArray(1);
    final AtomicLongArray la = new AtomicLongArray(1);
    final AtomicReferenceArray<Long> ra = new AtomicReferenceArray<Long>(1);
    final AtomicIntegerFieldUpdater<Lazy> iu = AtomicIntegerFieldUpdater.newUpdater(Lazy.class, "ii");
    final AtomicLongFieldUpdater<Lazy> lu = AtomicLongFieldUpdater.newUpdater(Lazy.class, "ll");
    final AtomicReferenceFieldUpdater<Lazy, Boolean> ru = AtomicReferenceFieldUpdater.newUpdater(Lazy.class, Boolean.class, "bb");
    Thread[] threads = { new Thread() {

        public void run() {
            b.lazySet(true);
        }
    }, new Thread() {

        public void run() {
            i.lazySet(2);
        }
    }, new Thread() {

        public void run() {
            l.lazySet(3L);
        }
    }, new Thread() {

        public void run() {
            r.lazySet(9L);
        }
    }, new Thread() {

        public void run() {
            ia.lazySet(0, 4);
        }
    }, new Thread() {

        public void run() {
            la.lazySet(0, 5L);
        }
    }, new Thread() {

        public void run() {
            ra.lazySet(0, 6L);
        }
    }, new Thread() {

        public void run() {
            iu.lazySet(z, 7);
        }
    }, new Thread() {

        public void run() {
            lu.lazySet(z, 8L);
        }
    }, new Thread() {

        public void run() {
            ru.lazySet(z, true);
        }
    } };
    for (Thread t : threads) t.start();
    for (Thread t : threads) t.join();
    if (!(b.get() == true && i.get() == 2 && l.get() == 3L && r.get() == 9L && ia.get(0) == 4 && la.get(0) == 5L && ra.get(0) == 6L && z.ii == 7 && z.ll == 8L && z.bb == true))
        throw new Exception("lazySet failed");
}

26. PageRankArrayStorageParallelSPI#compute()

View license
@Override
public void compute(int iterations, RelationshipType... relationshipTypes) {
    final ThreadToStatementContextBridge ctx = this.db.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class);
    final ReadOperations ops = ctx.get().readOperations();
    final IntPredicate isValidRelationshipType = relationshipTypeArrayToIntPredicate(ops, relationshipTypes);
    final int[] src = new int[nodeCount];
    dst = new AtomicIntegerArray(nodeCount);
    final int[] degrees = computeDegrees(ops);
    final RelationshipVisitor<RuntimeException> visitor = ( relId,  relTypeId,  startNode,  endNode) -> {
        if (isValidRelationshipType.test(relTypeId)) {
            dst.addAndGet((int) endNode, src[(int) startNode]);
        }
    };
    for (int iteration = 0; iteration < iterations; iteration++) {
        startIteration(src, dst, degrees);
        PrimitiveLongIterator rels = ops.relationshipsGetAll();
        runOperations(pool, rels, relCount, ops,  id -> ops.relationshipVisit(id, visitor));
    }
}

27. NaiveKMeans#cluster()

Project: JSAT
Source File: NaiveKMeans.java
View license
@Override
protected double cluster(final DataSet dataSet, List<Double> accelCacheInit, final int k, final List<Vec> means, final int[] assignment, final boolean exactTotal, ExecutorService threadpool, boolean returnError) {
    TrainableDistanceMetric.trainIfNeeded(dm, dataSet, threadpool);
    if (threadpool == null)
        threadpool = new FakeExecutor();
    final int blockSize = dataSet.getSampleSize() / SystemInfo.LogicalCores;
    final List<Vec> X = dataSet.getDataVectors();
    //done a wonky way b/c we want this as a final object for convinence, otherwise we may be stuck with null accel when we dont need to be
    final List<Double> accelCache;
    if (accelCacheInit == null) {
        if (threadpool instanceof FakeExecutor)
            accelCache = dm.getAccelerationCache(X);
        else
            accelCache = dm.getAccelerationCache(X, threadpool);
    } else
        accelCache = accelCacheInit;
    if (means.size() != k) {
        means.clear();
        if (threadpool instanceof FakeExecutor)
            means.addAll(selectIntialPoints(dataSet, k, dm, accelCache, rand, seedSelection));
        else
            means.addAll(selectIntialPoints(dataSet, k, dm, accelCache, rand, seedSelection, threadpool));
    }
    final List<List<Double>> meanQIs = new ArrayList<List<Double>>(k);
    //Use dense mean objects
    for (int i = 0; i < means.size(); i++) {
        if (dm.supportsAcceleration())
            meanQIs.add(dm.getQueryInfo(means.get(i)));
        else
            meanQIs.add(Collections.EMPTY_LIST);
        if (means.get(i).isSparse())
            means.set(i, new DenseVector(means.get(i)));
    }
    final List<Vec> meanSum = new ArrayList<Vec>(means.size());
    final AtomicIntegerArray meanCounts = new AtomicIntegerArray(means.size());
    for (int i = 0; i < k; i++) meanSum.add(new DenseVector(means.get(0).length()));
    final AtomicInteger changes = new AtomicInteger();
    //used to store local changes to the means and accumulated at the end
    final ThreadLocal<Vec[]> localMeanDeltas = new ThreadLocal<Vec[]>() {

        @Override
        protected Vec[] initialValue() {
            Vec[] deltas = new Vec[k];
            for (int i = 0; i < k; i++) deltas[i] = new DenseVector(means.get(0).length());
            return deltas;
        }
    };
    Arrays.fill(assignment, -1);
    do {
        changes.set(0);
        int extra = dataSet.getSampleSize() % SystemInfo.LogicalCores;
        int start = 0;
        final CountDownLatch latch = new CountDownLatch(SystemInfo.LogicalCores);
        while (start < dataSet.getSampleSize()) {
            final int s = start;
            final int end = start + blockSize + (extra-- > 0 ? 1 : 0);
            threadpool.submit(new Runnable() {

                @Override
                public void run() {
                    Vec[] deltas = localMeanDeltas.get();
                    double tmp;
                    for (int i = s; i < end; i++) {
                        final Vec x = X.get(i);
                        double minDist = Double.POSITIVE_INFINITY;
                        int min = -1;
                        for (int j = 0; j < means.size(); j++) {
                            tmp = dm.dist(i, means.get(j), meanQIs.get(j), X, accelCache);
                            if (tmp < minDist) {
                                minDist = tmp;
                                min = j;
                            }
                        }
                        if (assignment[i] == min)
                            continue;
                        //add change
                        deltas[min].mutableAdd(x);
                        meanCounts.incrementAndGet(min);
                        //remove from prev owner
                        if (assignment[i] >= 0) {
                            deltas[assignment[i]].mutableSubtract(x);
                            meanCounts.getAndDecrement(assignment[i]);
                        }
                        assignment[i] = min;
                        changes.incrementAndGet();
                    }
                    //accumulate deltas into globals
                    for (int i = 0; i < deltas.length; i++) synchronized (meanSum.get(i)) {
                        meanSum.get(i).mutableAdd(deltas[i]);
                        deltas[i].zeroOut();
                    }
                    latch.countDown();
                }
            });
            start = end;
        }
        try {
            latch.await();
            if (changes.get() == 0)
                break;
            for (int i = 0; i < k; i++) {
                meanSum.get(i).copyTo(means.get(i));
                means.get(i).mutableDivide(meanCounts.get(i));
                if (dm.supportsAcceleration())
                    meanQIs.set(i, dm.getQueryInfo(means.get(i)));
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(NaiveKMeans.class.getName()).log(Level.SEVERE, null, ex);
        }
    } while (changes.get() > 0);
    if (returnError) {
        double totalDistance = 0;
        if (saveCentroidDistance)
            nearestCentroidDist = new double[X.size()];
        else
            nearestCentroidDist = null;
        for (int i = 0; i < dataSet.getSampleSize(); i++) {
            double dist = dm.dist(i, means.get(assignment[i]), meanQIs.get(assignment[i]), X, accelCache);
            totalDistance += Math.pow(dist, 2);
            if (saveCentroidDistance)
                nearestCentroidDist[i] = dist;
        }
        return totalDistance;
    } else
        //who cares
        return 0;
}

28. IgniteCacheQueryNodeRestartSelfTest2#testRestarts()

View license
/**
     * @throws Exception If failed.
     */
public void testRestarts() throws Exception {
    int duration = 90 * 1000;
    int qryThreadNum = 4;
    // 4 + 2 = 6 nodes
    int restartThreadsNum = 2;
    final int nodeLifeTime = 2 * 1000;
    final int logFreq = 10;
    startGridsMultiThreaded(GRID_CNT);
    final AtomicIntegerArray locks = new AtomicIntegerArray(GRID_CNT);
    fillCaches();
    final List<List<?>> pRes = grid(0).cache("pu").query(new SqlFieldsQuery(PARTITIONED_QRY)).getAll();
    Thread.sleep(3000);
    assertEquals(pRes, grid(0).cache("pu").query(new SqlFieldsQuery(PARTITIONED_QRY)).getAll());
    final List<List<?>> rRes = grid(0).cache("co").query(new SqlFieldsQuery(REPLICATED_QRY)).getAll();
    assertFalse(pRes.isEmpty());
    assertFalse(rRes.isEmpty());
    final AtomicInteger qryCnt = new AtomicInteger();
    final AtomicBoolean qrysDone = new AtomicBoolean();
    IgniteInternalFuture<?> fut1 = multithreadedAsync(new CAX() {

        @Override
        public void applyx() throws IgniteCheckedException {
            GridRandom rnd = new GridRandom();
            while (!qrysDone.get()) {
                int g;
                do {
                    g = rnd.nextInt(locks.length());
                } while (!locks.compareAndSet(g, 0, 1));
                if (rnd.nextBoolean()) {
                    // Partitioned query.
                    IgniteCache<?, ?> cache = grid(g).cache("pu");
                    SqlFieldsQuery qry = new SqlFieldsQuery(PARTITIONED_QRY);
                    boolean smallPageSize = rnd.nextBoolean();
                    if (smallPageSize)
                        qry.setPageSize(3);
                    try {
                        assertEquals(pRes, cache.query(qry).getAll());
                    } catch (CacheException e) {
                        if (!smallPageSize)
                            e.printStackTrace();
                        assertTrue("On large page size must retry.", smallPageSize);
                        boolean failedOnRemoteFetch = false;
                        for (Throwable th = e; th != null; th = th.getCause()) {
                            if (!(th instanceof CacheException))
                                continue;
                            if (th.getMessage() != null && th.getMessage().startsWith("Failed to fetch data from node:")) {
                                failedOnRemoteFetch = true;
                                break;
                            }
                        }
                        if (!failedOnRemoteFetch) {
                            e.printStackTrace();
                            fail("Must fail inside of GridResultPage.fetchNextPage or subclass.");
                        }
                    }
                } else {
                    // Replicated query.
                    IgniteCache<?, ?> cache = grid(g).cache("co");
                    assertEquals(rRes, cache.query(new SqlFieldsQuery(REPLICATED_QRY)).getAll());
                }
                locks.set(g, 0);
                int c = qryCnt.incrementAndGet();
                if (c % logFreq == 0)
                    info("Executed queries: " + c);
            }
        }
    }, qryThreadNum, "query-thread");
    final AtomicInteger restartCnt = new AtomicInteger();
    final AtomicBoolean restartsDone = new AtomicBoolean();
    IgniteInternalFuture<?> fut2 = multithreadedAsync(new Callable<Object>() {

        @SuppressWarnings({ "BusyWait" })
        @Override
        public Object call() throws Exception {
            GridRandom rnd = new GridRandom();
            while (!restartsDone.get()) {
                int g;
                do {
                    g = rnd.nextInt(locks.length());
                } while (!locks.compareAndSet(g, 0, -1));
                log.info("Stop node: " + g);
                stopGrid(g);
                Thread.sleep(rnd.nextInt(nodeLifeTime));
                log.info("Start node: " + g);
                startGrid(g);
                Thread.sleep(rnd.nextInt(nodeLifeTime));
                locks.set(g, 0);
                int c = restartCnt.incrementAndGet();
                if (c % logFreq == 0)
                    info("Node restarts: " + c);
            }
            return true;
        }
    }, restartThreadsNum, "restart-thread");
    Thread.sleep(duration);
    info("Stopping..");
    restartsDone.set(true);
    fut2.get();
    info("Restarts stopped.");
    qrysDone.set(true);
    fut1.get();
    info("Queries stopped.");
}

29. IgniteCacheClientQueryReplicatedNodeRestartSelfTest#testRestarts()

View license
/**
     * @throws Exception If failed.
     */
public void testRestarts() throws Exception {
    int duration = 90 * 1000;
    int qryThreadNum = 5;
    // 2 of 4 data nodes
    int restartThreadsNum = 2;
    final int nodeLifeTime = 2 * 1000;
    final int logFreq = 10;
    startGridsMultiThreaded(GRID_CNT);
    // The last is client only.
    final AtomicIntegerArray locks = new AtomicIntegerArray(GRID_CNT - 1);
    fillCaches();
    final List<List<?>> pRes = grid(0).cache("pu").query(new SqlFieldsQuery(QRY)).getAll();
    Thread.sleep(3000);
    assertEquals(pRes, grid(0).cache("pu").query(new SqlFieldsQuery(QRY)).getAll());
    assertFalse(pRes.isEmpty());
    final AtomicInteger qryCnt = new AtomicInteger();
    final AtomicBoolean qrysDone = new AtomicBoolean();
    final List<Integer> cacheSize = new ArrayList<>(4);
    for (int i = 0; i < GRID_CNT - 1; i++) {
        int j = 0;
        for (String cacheName : F.asList("co", "pr", "pe", "pu")) {
            IgniteCache<?, ?> cache = grid(i).cache(cacheName);
            assertClient(cache, false);
            if (i == 0)
                cacheSize.add(cache.size());
            else
                assertEquals(cacheSize.get(j++).intValue(), cache.size());
        }
    }
    int j = 0;
    for (String cacheName : F.asList("co", "pr", "pe", "pu")) {
        IgniteCache<?, ?> cache = grid(GRID_CNT - 1).cache(cacheName);
        assertClient(cache, true);
        assertEquals(cacheSize.get(j++).intValue(), cache.size());
    }
    final IgniteCache<?, ?> clientCache = grid(GRID_CNT - 1).cache("pu");
    IgniteInternalFuture<?> fut1 = multithreadedAsync(new CAX() {

        @Override
        public void applyx() throws IgniteCheckedException {
            GridRandom rnd = new GridRandom();
            while (!qrysDone.get()) {
                SqlFieldsQuery qry = new SqlFieldsQuery(QRY);
                boolean smallPageSize = rnd.nextBoolean();
                if (smallPageSize)
                    qry.setPageSize(3);
                List<List<?>> res;
                try {
                    res = clientCache.query(qry).getAll();
                } catch (CacheException e) {
                    assertTrue("On large page size must retry.", smallPageSize);
                    boolean failedOnRemoteFetch = false;
                    for (Throwable th = e; th != null; th = th.getCause()) {
                        if (!(th instanceof CacheException))
                            continue;
                        if (th.getMessage() != null && th.getMessage().startsWith("Failed to fetch data from node:")) {
                            failedOnRemoteFetch = true;
                            break;
                        }
                    }
                    if (!failedOnRemoteFetch) {
                        e.printStackTrace();
                        fail("Must fail inside of GridResultPage.fetchNextPage or subclass.");
                    }
                    res = FAKE;
                }
                if (res != FAKE && !res.equals(pRes)) {
                    int j = 0;
                    // Check for data loss.
                    for (String cacheName : F.asList("co", "pr", "pe", "pu")) {
                        assertEquals(cacheName, cacheSize.get(j++).intValue(), grid(GRID_CNT - 1).cache(cacheName).size());
                    }
                    // Fail with nice message.
                    assertEquals(pRes, res);
                }
                int c = qryCnt.incrementAndGet();
                if (c % logFreq == 0)
                    info("Executed queries: " + c);
            }
        }
    }, qryThreadNum, "query-thread");
    final AtomicInteger restartCnt = new AtomicInteger();
    final AtomicBoolean restartsDone = new AtomicBoolean();
    IgniteInternalFuture<?> fut2 = multithreadedAsync(new Callable<Object>() {

        @SuppressWarnings({ "BusyWait" })
        @Override
        public Object call() throws Exception {
            GridRandom rnd = new GridRandom();
            while (!restartsDone.get()) {
                int g;
                do {
                    g = rnd.nextInt(locks.length());
                } while (!locks.compareAndSet(g, 0, -1));
                log.info("Stop node: " + g);
                stopGrid(g);
                Thread.sleep(rnd.nextInt(nodeLifeTime));
                log.info("Start node: " + g);
                startGrid(g);
                Thread.sleep(rnd.nextInt(nodeLifeTime));
                locks.set(g, 0);
                int c = restartCnt.incrementAndGet();
                if (c % logFreq == 0)
                    info("Node restarts: " + c);
            }
            return true;
        }
    }, restartThreadsNum, "restart-thread");
    Thread.sleep(duration);
    info("Stopping..");
    restartsDone.set(true);
    fut2.get();
    info("Restarts stopped.");
    qrysDone.set(true);
    fut1.get();
    info("Queries stopped.");
}