Example usage for java.util.concurrent.atomic AtomicInteger incrementAndGet

List of usage examples for java.util.concurrent.atomic AtomicInteger incrementAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger incrementAndGet.

Prototype

public final int incrementAndGet() 

Source Link

Document

Atomically increments the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:org.apache.pulsar.broker.service.PersistentQueueE2ETest.java

@Test
public void testConsumersWithDifferentPermits() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/shared-topic4";
    final String subName = "sub4";
    final int numMsgs = 10000;

    final AtomicInteger msgCountConsumer1 = new AtomicInteger(0);
    final AtomicInteger msgCountConsumer2 = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(numMsgs);

    int recvQ1 = 10;
    ConsumerConfiguration conf1 = new ConsumerConfiguration();
    conf1.setSubscriptionType(SubscriptionType.Shared);
    conf1.setReceiverQueueSize(recvQ1);//  www . j  a  va  2  s . c  o  m
    conf1.setMessageListener((consumer, msg) -> {
        msgCountConsumer1.incrementAndGet();
        try {
            consumer.acknowledge(msg);
            latch.countDown();
        } catch (PulsarClientException e) {
            fail("Should not fail");
        }
    });

    int recvQ2 = 1;
    ConsumerConfiguration conf2 = new ConsumerConfiguration();
    conf2.setSubscriptionType(SubscriptionType.Shared);
    conf2.setReceiverQueueSize(recvQ2);
    conf2.setMessageListener((consumer, msg) -> {
        msgCountConsumer2.incrementAndGet();
        try {
            consumer.acknowledge(msg);
            latch.countDown();
        } catch (PulsarClientException e) {
            fail("Should not fail");
        }
    });

    Consumer consumer1 = pulsarClient.subscribe(topicName, subName, conf1);
    Consumer consumer2 = pulsarClient.subscribe(topicName, subName, conf2);

    List<CompletableFuture<MessageId>> futures = Lists.newArrayListWithCapacity(numMsgs);
    ProducerConfiguration conf = new ProducerConfiguration();
    conf.setMaxPendingMessages(numMsgs + 1);
    Producer producer = pulsarClient.createProducer(topicName, conf);
    for (int i = 0; i < numMsgs; i++) {
        String message = "msg-" + i;
        futures.add(producer.sendAsync(message.getBytes()));
    }
    FutureUtil.waitForAll(futures).get();
    producer.close();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(msgCountConsumer1.get(), numMsgs - numMsgs / (recvQ1 + recvQ2), numMsgs * 0.1);
    assertEquals(msgCountConsumer2.get(), numMsgs / (recvQ1 + recvQ2), numMsgs * 0.1);

    consumer1.close();
    consumer2.close();
    admin.persistentTopics().delete(topicName);
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testBasic() throws Exception {
    final Timing timing = new Timing();
    final List<Closeable> closeables = Lists.newArrayList();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {/* w  ww  .ja v  a  2s . c o m*/
        closeables.add(client);
        client.start();

        final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
        final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
        final AtomicInteger count = new AtomicInteger(0);
        final AtomicInteger max = new AtomicInteger(0);
        List<Future<Void>> futures = Lists.newArrayList();
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < QTY; ++i) {
            Future<Void> future = service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(10, TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postLeaveLatch));

                    return null;
                }
            });
            futures.add(future);
        }

        for (Future<Void> f : futures) {
            f.get();
        }
        Assert.assertEquals(count.get(), 0);
        Assert.assertEquals(max.get(), QTY);
    } finally {
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexAugmentTest.java

@Test
public void skipDefaultOnlyUsingAugmentors() throws Exception {
    //setup repo and index
    NodeTypeRegistry.register(root, IOUtils.toInputStream(TestUtil.TEST_NODE_TYPE), "test nodeType");
    Tree props = createIndex(TestUtil.NT_TEST);
    Tree prop = props.addChild("foo1");
    prop.setProperty(LuceneIndexConstants.PROP_INDEX, true);
    prop = props.addChild("foo2");
    prop.setProperty(LuceneIndexConstants.PROP_NAME, "subChild/foo2");
    prop.setProperty(LuceneIndexConstants.PROP_INDEX, true);
    root.commit();// ww  w .j a v a  2s  .  c  om

    //setup augmentors
    final AtomicInteger indexingCounter = new AtomicInteger(0);
    factory.indexFieldProvider = new IndexFieldProvider() {
        @Nonnull
        @Override
        public Iterable<Field> getAugmentedFields(String path, NodeState document, NodeState indexDefinition) {
            indexingCounter.incrementAndGet();
            return IndexFieldProvider.DEFAULT.getAugmentedFields(path, document, indexDefinition);
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };
    final AtomicInteger queryingCounter = new AtomicInteger(0);
    factory.fulltextQueryTermsProvider = new FulltextQueryTermsProvider() {
        @Override
        public Query getQueryTerm(String text, Analyzer analyzer, NodeState indexDefinition) {
            queryingCounter.set(1);
            return null;
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };

    //add content
    Tree node1 = createNodeWithType(root.getTree("/"), "node1", TestUtil.NT_TEST);
    node1.setProperty("foo1", "bar1");
    node1.addChild("subChild").setProperty("foo2", "bar2");
    root.commit();

    //indexing assertions
    assertEquals("Indexing augment should get called once", 1, indexingCounter.get());
    assertEquals("No docs should get indexed (augmentor hasn't added any field)", 0,
            getSearcher().getIndexReader().numDocs());

    String query = "EXPLAIN SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE [foo1]='bar1'";
    List<String> paths = executeQuery(query, SQL2);
    assertTrue("indexed prop name shouldn't decide query plan (" + paths.get(0) + ")",
            paths.get(0).contains("/* no-index "));

    query = "EXPLAIN SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE [subChild/foo2]='bar2'";
    paths = executeQuery(query, SQL2);
    assertTrue("indexed prop name shouldn't decide query plan (" + paths.get(0) + ")",
            paths.get(0).contains("/* no-index "));
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexAugmentTest.java

@Test
public void propertyIndexUsingAugmentors() throws Exception {
    //setup repo and index
    NodeTypeRegistry.register(root, IOUtils.toInputStream(TestUtil.TEST_NODE_TYPE), "test nodeType");
    Tree props = createIndex(TestUtil.NT_TEST);
    TestUtil.enablePropertyIndex(props, "foo1", false);
    TestUtil.enablePropertyIndex(props, "subChild/foo2", false);
    root.commit();//ww  w.j  a  v  a  2s .c  o  m

    //setup augmentors
    final AtomicInteger indexingCounter = new AtomicInteger(0);
    factory.indexFieldProvider = new IndexFieldProvider() {
        @Nonnull
        @Override
        public Iterable<Field> getAugmentedFields(String path, NodeState document, NodeState indexDefinition) {
            indexingCounter.incrementAndGet();
            return IndexFieldProvider.DEFAULT.getAugmentedFields(path, document, indexDefinition);
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };
    final AtomicInteger queryingCounter = new AtomicInteger(0);
    factory.fulltextQueryTermsProvider = new FulltextQueryTermsProvider() {
        @Override
        public Query getQueryTerm(String text, Analyzer analyzer, NodeState indexDefinition) {
            queryingCounter.set(1);
            return null;
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };

    //add content
    Tree node1 = createNodeWithType(root.getTree("/"), "node1", TestUtil.NT_TEST);
    node1.setProperty("foo1", "bar1");
    node1.addChild("subChild").setProperty("foo2", "bar2");
    root.commit();

    //indexing assertions
    assertEquals("Indexing augment should get called once", 1, indexingCounter.get());

    String query = "SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE [foo1]='bar1'";
    executeQuery(query, SQL2);
    assertEquals("Query augmentor should not get called for property constraints", 0, queryingCounter.get());
    query = "EXPLAIN " + query;
    List<String> paths = executeQuery(query, SQL2, false);
    assertTrue("property index should have made the index selected (" + paths.get(0) + ")",
            paths.get(0).contains("/* lucene:test-index("));

    query = "SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE [subChild/foo2]='bar2'";
    executeQuery(query, SQL2);
    assertEquals("Query augmentor should not get called for property constraints", 0, queryingCounter.get());
    query = "EXPLAIN " + query;
    paths = executeQuery(query, SQL2);
    assertTrue("property index should have made the index selected (" + paths.get(0) + ")",
            paths.get(0).contains("/* lucene:test-index("));
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexAugmentTest.java

@Test
public void fulltextIndexUsingAugmentors() throws Exception {
    //setup repo and index
    NodeTypeRegistry.register(root, IOUtils.toInputStream(TestUtil.TEST_NODE_TYPE), "test nodeType");
    Tree props = createIndex(TestUtil.NT_TEST);
    TestUtil.enableForFullText(props, "foo1");
    TestUtil.enableForFullText(props, "subChild/foo2");
    root.commit();/*from  w ww  .j a v  a 2s .  c o  m*/

    //setup augmentors
    final AtomicInteger indexingCounter = new AtomicInteger(0);
    factory.indexFieldProvider = new IndexFieldProvider() {
        @Nonnull
        @Override
        public Iterable<Field> getAugmentedFields(String path, NodeState document, NodeState indexDefinition) {
            indexingCounter.incrementAndGet();
            return IndexFieldProvider.DEFAULT.getAugmentedFields(path, document, indexDefinition);
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };
    final AtomicInteger queryingCounter = new AtomicInteger(0);
    factory.fulltextQueryTermsProvider = new FulltextQueryTermsProvider() {
        @Override
        public Query getQueryTerm(String text, Analyzer analyzer, NodeState indexDefinition) {
            queryingCounter.set(1);
            return null;
        }

        @Nonnull
        @Override
        public Set<String> getSupportedTypes() {
            return Collections.singleton(TestUtil.NT_TEST);
        }
    };

    //add content
    Tree node1 = createNodeWithType(root.getTree("/"), "node1", TestUtil.NT_TEST);
    node1.setProperty("foo1", "bar1");
    node1.addChild("subChild").setProperty("foo2", "bar2");
    root.commit();

    //indexing assertions
    assertEquals("Indexing augment should get called once", 1, indexingCounter.get());

    String query = "SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE CONTAINS(*, 'bar1')";
    executeQuery(query, SQL2);
    assertEquals("Query augmentor should get called for full text constraints", 1, queryingCounter.get());
    queryingCounter.set(0);
    query = "EXPLAIN " + query;
    List<String> paths = executeQuery(query, SQL2, false);
    assertEquals("Query augmentor should get called for full text constraints", 1, queryingCounter.get());
    assertTrue("property index should have made the index selected (" + paths.get(0) + ")",
            paths.get(0).contains("/* lucene:test-index("));

    queryingCounter.set(0);
    query = "SELECT [jcr:path] from [" + TestUtil.NT_TEST + "] WHERE CONTAINS(*, 'bar2')";
    executeQuery(query, SQL2);
    assertEquals("Query augmentor should get called for full text constraints", 1, queryingCounter.get());
    queryingCounter.set(0);
    query = "EXPLAIN " + query;
    paths = executeQuery(query, SQL2, false);
    assertEquals("Query augmentor should get called for full text constraints", 1, queryingCounter.get());
    assertTrue("property index should have made the index selected (" + paths.get(0) + ")",
            paths.get(0).contains("/* lucene:test-index("));
}

From source file:com.github.tomakehurst.wiremock.matching.EqualToXmlPattern.java

@Override
public MatchResult match(final String value) {
    return new MatchResult() {
        @Override//from ww w  .  ja  v  a  2 s .c  om
        public boolean isExactMatch() {
            if (isNullOrEmpty(value)) {
                return false;
            }

            try {
                Diff diff = DiffBuilder.compare(Input.from(expectedValue)).withTest(value)
                        .withComparisonController(ComparisonControllers.StopWhenDifferent).ignoreWhitespace()
                        .ignoreComments().withDifferenceEvaluator(IGNORE_UNCOUNTED_COMPARISONS).build();

                return !diff.hasDifferences();
            } catch (XMLUnitException e) {
                notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue
                        + "\n\nActual:\n" + value);
                return false;
            }
        }

        @Override
        public double getDistance() {
            if (isNullOrEmpty(value)) {
                return 1.0;
            }

            final AtomicInteger totalComparisons = new AtomicInteger(0);
            final AtomicInteger differences = new AtomicInteger(0);

            Diff diff = null;
            try {
                diff = DiffBuilder.compare(Input.from(expectedValue)).withTest(value).ignoreWhitespace()
                        .ignoreComments().withDifferenceEvaluator(IGNORE_UNCOUNTED_COMPARISONS)
                        .withComparisonListeners(new ComparisonListener() {
                            @Override
                            public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) {
                                if (COUNTED_COMPARISONS.contains(comparison.getType())
                                        && comparison.getControlDetails().getValue() != null) {
                                    totalComparisons.incrementAndGet();
                                    if (outcome == ComparisonResult.DIFFERENT) {
                                        differences.incrementAndGet();
                                    }
                                }
                            }
                        }).build();
            } catch (XMLUnitException e) {
                notifier().info("Failed to process XML. " + e.getMessage() + "\nExpected:\n" + expectedValue
                        + "\n\nActual:\n" + value);
                return 1.0;
            }

            notifier().info(Joiner.on("\n").join(diff.getDifferences()));

            return differences.doubleValue() / totalComparisons.doubleValue();
        }
    };
}

From source file:org.apache.hadoop.hbase.mapreduce.TestLoadIncrementalHFilesSplitRecovery.java

/**
 * Test that shows that exception thrown from the RS side will result in an
 * exception on the LIHFile client.//from  ww  w.j  a  va  2  s.c o  m
 */
@Test(expected = IOException.class)
public void testBulkLoadPhaseFailure() throws Exception {
    String table = "bulkLoadPhaseFailure";
    setupTable(table, 10);

    final AtomicInteger attmptedCalls = new AtomicInteger();
    final AtomicInteger failedCalls = new AtomicInteger();
    util.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2);
    try {
        LoadIncrementalHFiles lih = new LoadIncrementalHFiles(util.getConfiguration()) {

            protected List<LoadQueueItem> tryAtomicRegionLoad(final HConnection conn, TableName tableName,
                    final byte[] first, Collection<LoadQueueItem> lqis) throws IOException {
                int i = attmptedCalls.incrementAndGet();
                if (i == 1) {
                    HConnection errConn = null;
                    try {
                        errConn = getMockedConnection(util.getConfiguration());
                    } catch (Exception e) {
                        LOG.fatal("mocking cruft, should never happen", e);
                        throw new RuntimeException("mocking cruft, should never happen");
                    }
                    failedCalls.incrementAndGet();
                    return super.tryAtomicRegionLoad(errConn, tableName, first, lqis);
                }

                return super.tryAtomicRegionLoad(conn, tableName, first, lqis);
            }
        };

        // create HFiles for different column families
        Path dir = buildBulkFiles(table, 1);
        HTable t = new HTable(util.getConfiguration(), Bytes.toBytes(table));
        lih.doBulkLoad(dir, t);
    } finally {
        util.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
                HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
    }

    fail("doBulkLoad should have thrown an exception");
}

From source file:org.apache.kylin.storage.cache.DynamicCacheTest.java

@Test
public void basicTest() {

    final StorageContext context = new StorageContext();
    final List<TblColRef> groups = StorageMockUtils.buildGroups();
    final TblColRef partitionCol = groups.get(0);
    final List<FunctionDesc> aggregations = StorageMockUtils.buildAggregations();
    final TupleInfo tupleInfo = StorageMockUtils.newTupleInfo(groups, aggregations);

    SQLDigest sqlDigest = new SQLDigest("default.test_kylin_fact", null, null, Lists.<TblColRef>newArrayList(),
            groups, Lists.newArrayList(partitionCol), Lists.<TblColRef>newArrayList(), aggregations,
            new ArrayList<MeasureDesc>(), new ArrayList<SQLDigest.OrderEnum>());

    ITuple aTuple = new TsOnlyTuple(partitionCol, "2011-02-01");
    ITuple bTuple = new TsOnlyTuple(partitionCol, "2012-02-01");
    final List<ITuple> allTuples = Lists.newArrayList(aTuple, bTuple);

    //counts for verifying
    final AtomicInteger underlyingSEHitCount = new AtomicInteger(0);
    final List<Integer> returnedRowPerSearch = Lists.newArrayList();

    CacheFledgedDynamicQuery dynamicCache = new CacheFledgedDynamicQuery(new ICachableStorageQuery() {
        @Override//from w w  w  .  j a  v  a2s . co m
        public ITupleIterator search(StorageContext context, SQLDigest sqlDigest, TupleInfo returnTupleInfo) {
            Range<Long> tsRagneInQuery = TsConditionExtractor.extractTsCondition(partitionCol,
                    sqlDigest.filter);
            List<ITuple> ret = Lists.newArrayList();
            for (ITuple tuple : allTuples) {
                if (tsRagneInQuery.contains(Tuple.getTs(tuple, partitionCol))) {
                    ret.add(tuple);
                }
            }

            underlyingSEHitCount.incrementAndGet();
            returnedRowPerSearch.add(ret.size());

            return new SimpleTupleIterator(ret.iterator());
        }

        @Override
        public boolean isDynamic() {
            return true;
        }

        @Override
        public Range<Long> getVolatilePeriod() {
            return Ranges.greaterThan(DateFormat.stringToMillis("2011-02-01"));
        }

        @Override
        public String getStorageUUID() {
            return "111ca32a-a33e-4b69-12aa-0bb8b1f8c191";
        }
    }, partitionCol);

    sqlDigest.filter = StorageMockUtils.buildTs2010Filter(groups.get(0));
    ITupleIterator firstIterator = dynamicCache.search(context, sqlDigest, tupleInfo);
    IdentityHashMap<ITuple, Void> firstResults = new IdentityHashMap<>();
    while (firstIterator.hasNext()) {
        firstResults.put(firstIterator.next(), null);
    }
    firstIterator.close();

    sqlDigest.filter = StorageMockUtils.buildTs2011Filter(groups.get(0));
    ITupleIterator secondIterator = dynamicCache.search(context, sqlDigest, tupleInfo);
    IdentityHashMap<ITuple, Void> secondResults = new IdentityHashMap<>();
    while (secondIterator.hasNext()) {
        secondResults.put(secondIterator.next(), null);
    }
    secondIterator.close();

    Assert.assertEquals(2, firstResults.size());
    IdentityUtils.collectionReferenceEquals(firstResults.keySet(), secondResults.keySet());
    Assert.assertEquals(2, underlyingSEHitCount.get());
    Assert.assertEquals(new Integer(2), returnedRowPerSearch.get(0));
    Assert.assertEquals(new Integer(1), returnedRowPerSearch.get(1));
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldNotExhaustThreads() throws Exception {
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2, testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().executorService(executorService)
            .scheduledExecutorService(executorService).create();

    final AtomicInteger count = new AtomicInteger(0);
    assertTrue(IntStream.range(0, 1000).mapToObj(i -> gremlinExecutor.eval("1+1")).allMatch(f -> {
        try {//  w  ww .ja  va2 s .  c o  m
            return (Integer) f.get() == 2;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            count.incrementAndGet();
        }
    }));

    assertEquals(1000, count.intValue());

    executorService.shutdown();
    executorService.awaitTermination(30000, TimeUnit.MILLISECONDS);
}

From source file:com.github.gfx.android.orma.example.fragment.BenchmarkFragment.java

Single<Result> startSelectAllWithRealm() {
    return Single.fromCallable(() -> {
        long result = runWithBenchmark(() -> {
            AtomicInteger count = new AtomicInteger();
            Realm realm = Realm.getDefaultInstance();
            RealmResults<RealmTodo> results = realm.where(RealmTodo.class).findAllSorted("createdTime",
                    Sort.ASCENDING);// w ww  .j  a v a 2 s .c om
            for (RealmTodo todo : results) {
                @SuppressWarnings("unused")
                String title = todo.getTitle();
                @SuppressWarnings("unused")
                String content = todo.getContent();
                @SuppressWarnings("unused")
                Date createdTime = todo.getCreatedTime();

                count.incrementAndGet();
            }
            if (results.size() != count.get()) {
                throw new AssertionError("unexpected get: " + count.get());
            }
            realm.close();

            Log.d(TAG, "Realm/forEachAll count: " + count);
        });
        return new Result("Realm/forEachAll", result);
    });
}