java.util.concurrent.atomic.AtomicInteger

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

1. VOA#main()

Project: HtmlExtractor
File: VOA.java
public static void main(String[] args) throws Exception {
    String sourceDir = "/Users/ysc/workspace/HtmlExtractor/html-extractor/src/main/resources/voa/";
    String targetDir = "/Users/ysc/??????/VOA/";
    AtomicInteger i = new AtomicInteger();
    i.set(0);
    download(sourceDir + "HowAmericaElects.txt", targetDir + "How America Elects").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "EnglishInAMinute.txt", targetDir + "English in a Minute").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "EnglishAtTheMovies.txt", targetDir + "English @ the Movies").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "EverydayGrammarTV.txt", targetDir + "Everyday Grammar TV").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "LearningEnglishTV.txt", targetDir + "Learning English TV").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "NewsWords.txt", targetDir + "News Words").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "PeopleInAmerica.txt", targetDir + "People In America").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "Let'sLearnEnglish.txt", targetDir + "Let's Learn English").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "What'sTrendingToday.txt", targetDir + "What's Trending Today").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "WordsandTheirStories.txt", targetDir + "Words and Their Stories").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "PersonalTechnology.txt", targetDir + "Personal Technology").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "ScienceintheNews.txt", targetDir + "Science in the News").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "TheMakingofaNation.txt", targetDir + "The Making of a Nation").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "ThisIsAmerica.txt", targetDir + "This Is America").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "Education.txt", targetDir + "Education").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "EverydayGrammar.txt", targetDir + "Everyday Grammar").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "HealthLifestyle.txt", targetDir + "Health & Lifestyle").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "IntheNews.txt", targetDir + "In the News").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "America'sNationalParks.txt", targetDir + "America's National Parks").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "AmericanMosaic.txt", targetDir + "American Mosaic").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "AmericanStories.txt", targetDir + "American Stories").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
    i.set(0);
    download(sourceDir + "AsItIs.txt", targetDir + "As It Is").stream().sorted().forEach( item -> System.out.println(i.incrementAndGet() + ". " + item));
}

2. BoltInstanceTest#after()

Project: heron
File: BoltInstanceTest.java
@After
public void after() throws Exception {
    UnitTestHelper.clearSingletonRegistry();
    ackCount = new AtomicInteger(0);
    failCount = new AtomicInteger(0);
    tupleExecutedCount = new AtomicInteger(0);
    receivedStrings = null;
    testLooper.exitLoop();
    slaveLooper.exitLoop();
    threadsPool.shutdownNow();
    physicalPlan = null;
    testLooper = null;
    slaveLooper = null;
    outStreamQueue = null;
    inStreamQueue = null;
    slave = null;
    threadsPool = null;
}

3. ServiceDiscoveryImplTest#setup()

Project: qbit
File: ServiceDiscoveryImplTest.java
@Before
public void setup() {
    servicePoolChangedCalled = new AtomicInteger();
    serviceAdded = new AtomicInteger();
    serviceRemoved = new AtomicInteger();
    servicePoolChangedServiceName = new AtomicReference<>();
    servicePoolChangedServiceNameFromListener = new AtomicReference<>();
    registeredEndpointDefinitions = new ConcurrentHashSet<>(100);
    healthCheckIns = new ConcurrentHashSet<>(100);
    serviceDiscovery = new ServiceDiscoveryImpl(createPeriodicScheduler(10), eventChannel, provider, null, servicePoolListener, null, 5, 5);
    healthyServices = new AtomicReference<>();
    serviceDiscovery.start();
}

4. TestContinuations#testOnSuccessCalled()

Project: parseq
File: TestContinuations.java
@Test
public void testOnSuccessCalled() {
    final AtomicInteger sequence = new AtomicInteger(0);
    final AtomicInteger action = new AtomicInteger();
    final AtomicInteger onSuccess = new AtomicInteger();
    Continuations CONT = new Continuations();
    CONT.submit(() -> {
        action.set(sequence.incrementAndGet());
    });
    CONT.submit(() -> {
        onSuccess.set(sequence.incrementAndGet());
    });
    assertEquals(action.get(), 1);
    assertEquals(onSuccess.get(), 2);
}

5. IndexedRingBufferTest#addThousands()

Project: RxJava
File: IndexedRingBufferTest.java
@Test
public void addThousands() {
    String s = "s";
    IndexedRingBuffer<String> list = IndexedRingBuffer.getInstance();
    for (int i = 0; i < 10000; i++) {
        list.add(s);
    }
    AtomicInteger c = new AtomicInteger();
    list.forEach(newCounterAction(c));
    assertEquals(10000, c.get());
    list.remove(5000);
    c.set(0);
    list.forEach(newCounterAction(c));
    assertEquals(9999, c.get());
    list.add("one");
    list.add("two");
    c.set(0);
    //        list.forEach(print());
    list.forEach(newCounterAction(c));
    assertEquals(10001, c.get());
}

6. SimpleTextSimilarity#scoreImpl()

Project: word
File: SimpleTextSimilarity.java
/**
     * ???????
     * @param words1 ???1
     * @param words2 ???2
     * @return ?????
     */
@Override
protected double scoreImpl(List<Word> words1, List<Word> words2) {
    //?????1?????
    AtomicInteger words1Length = new AtomicInteger();
    words1.parallelStream().forEach( word -> words1Length.addAndGet(word.getText().length()));
    //?????2?????
    AtomicInteger words2Length = new AtomicInteger();
    words2.parallelStream().forEach( word -> words2Length.addAndGet(word.getText().length()));
    //?????1????2??????????
    words1.retainAll(words2);
    AtomicInteger intersectionLength = new AtomicInteger();
    words1.parallelStream().forEach( word -> {
        intersectionLength.addAndGet(word.getText().length());
    });
    double score = intersectionLength.get() / (double) Math.max(words1Length.get(), words2Length.get());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("???1??????" + words1Length.get());
        LOGGER.debug("???2??????" + words2Length.get());
        LOGGER.debug("???1?2???????????" + intersectionLength.get());
        LOGGER.debug("?????=" + intersectionLength.get() + "/(double)Math.max(" + words1Length.get() + ", " + words1Length.get() + ")=" + score);
    }
    return score;
}

7. TestConcurrentUseOfDefaultManagerConnection#setUp()

Project: asterisk-java
File: TestConcurrentUseOfDefaultManagerConnection.java
@Override
protected void setUp() throws Exception {
    dmc = new DefaultManagerConnection();
    dmc.setUsername("manager");
    dmc.setPassword("obelisk");
    dmc.setHostname("pbx0");
    succeeded = new AtomicInteger(0);
    failed = new AtomicInteger(0);
    total = new AtomicInteger(0);
    dmc.login();
}

8. UniqueVariableNamer#nullSafeIterGet()

Project: transfuse
File: UniqueVariableNamer.java
private int nullSafeIterGet(String name) {
    AtomicInteger result = nameMap.get(name);
    if (result == null) {
        AtomicInteger value = new AtomicInteger();
        result = nameMap.putIfAbsent(name, value);
        if (result == null) {
            result = value;
        }
    }
    return result.getAndIncrement();
}

9. ClassNamer#get()

Project: transfuse
File: ClassNamer.java
private int get(String name) {
    AtomicInteger result = nameMap.get(name);
    if (result == null) {
        AtomicInteger value = new AtomicInteger();
        result = nameMap.putIfAbsent(name, value);
        if (result == null) {
            result = value;
        }
    }
    return result.getAndIncrement();
}

10. CountLatchTest#supportsIncrementingAndDecrementing()

Project: totallylazy
File: CountLatchTest.java
@Test
public void supportsIncrementingAndDecrementing() throws Exception {
    final AtomicInteger number = new AtomicInteger();
    final CountLatch latch = new CountLatch();
    latch.countUp();
    assertThat(latch.count(), is(1));
    ExecutorService executorService = NamedExecutors.newCachedThreadPool(getClass());
    for (final AtomicInteger atomicInteger : repeat(number).take(5)) {
        latch.countUp();
        executorService.submit(() -> {
            atomicInteger.incrementAndGet();
            latch.countDown();
        });
    }
    latch.countDown();
    latch.await();
    assertThat(latch.count(), is(0));
    assertThat(number.get(), is(5));
}

11. TitanGraphTest#executeSerialTransaction()

Project: titan
File: TitanGraphTest.java
private int executeSerialTransaction(final TransactionJob job, int number) {
    final AtomicInteger txSuccess = new AtomicInteger(0);
    for (int i = 0; i < number; i++) {
        TitanTransaction tx = graph.newTransaction();
        try {
            job.run(tx);
            tx.commit();
            txSuccess.incrementAndGet();
        } catch (Exception ex) {
            tx.rollback();
            ex.printStackTrace();
        }
    }
    return txSuccess.get();
}

12. OnSubscribeDoOnEmptyTest#subscriberStateTest()

Project: rxjava-extras
File: OnSubscribeDoOnEmptyTest.java
@Test
public void subscriberStateTest() {
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicInteger callCount = new AtomicInteger(0);
    Observable<Integer> o = Observable.defer(new Func0<Observable<Integer>>() {

        @Override
        public Observable<Integer> call() {
            return Observable.range(1, counter.getAndIncrement() % 2);
        }
    }).compose(Transformers.<Integer>doOnEmpty(Actions.increment0(callCount)));
    o.subscribe();
    o.subscribe();
    o.subscribe();
    o.subscribe();
    o.subscribe();
    assert (callCount.get() == 3);
}

13. OnSubscribeCacheResetableTest#test()

Project: rxjava-extras
File: OnSubscribeCacheResetableTest.java
@Test
public void test() {
    final AtomicInteger completedCount = new AtomicInteger();
    final AtomicInteger emissionCount = new AtomicInteger();
    CachedObservable<Integer> cached = Obs.cache(Observable.just(1).doOnCompleted(Actions.increment0(completedCount)));
    Observable<Integer> o = cached.doOnNext(Actions.increment1(emissionCount));
    o.subscribe();
    assertEquals(1, completedCount.get());
    assertEquals(1, emissionCount.get());
    o.subscribe();
    assertEquals(1, completedCount.get());
    assertEquals(2, emissionCount.get());
    cached.reset();
    o.subscribe();
    assertEquals(2, completedCount.get());
    assertEquals(3, emissionCount.get());
}

14. IndexedRingBufferTest#removeEnd()

Project: RxJava
File: IndexedRingBufferTest.java
@Test
public void removeEnd() {
    IndexedRingBuffer<LSubscription> list = IndexedRingBuffer.getInstance();
    list.add(new LSubscription(1));
    int n2 = list.add(new LSubscription(2));
    final AtomicInteger c = new AtomicInteger();
    list.forEach(newCounterAction(c));
    assertEquals(2, c.get());
    list.remove(n2);
    final AtomicInteger c2 = new AtomicInteger();
    list.forEach(newCounterAction(c2));
    assertEquals(1, c2.get());
}

15. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteSyncObservables()

Project: RxJava
File: OperatorZipTest.java
@Test
public void testDownstreamBackpressureRequestsWithInfiniteSyncObservables() {
    AtomicInteger generatedA = new AtomicInteger();
    AtomicInteger generatedB = new AtomicInteger();
    Observable<Integer> o1 = createInfiniteObservable(generatedA);
    Observable<Integer> o2 = createInfiniteObservable(generatedB);
    TestSubscriber<String> ts = new TestSubscriber<String>();
    Observable.zip(o1, o2, new Func2<Integer, Integer, String>() {

        @Override
        public String call(Integer t1, Integer t2) {
            return t1 + "-" + t2;
        }
    }).observeOn(Schedulers.computation()).take(RxRingBuffer.SIZE * 2).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
    System.out.println("Generated => A: " + generatedA.get() + " B: " + generatedB.get());
    assertTrue(generatedA.get() < (RxRingBuffer.SIZE * 4));
    assertTrue(generatedB.get() < (RxRingBuffer.SIZE * 4));
}

16. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteAsyncObservables()

Project: RxJava
File: OperatorZipTest.java
@Test
public void testDownstreamBackpressureRequestsWithInfiniteAsyncObservables() {
    AtomicInteger generatedA = new AtomicInteger();
    AtomicInteger generatedB = new AtomicInteger();
    Observable<Integer> o1 = createInfiniteObservable(generatedA).subscribeOn(Schedulers.computation());
    Observable<Integer> o2 = createInfiniteObservable(generatedB).subscribeOn(Schedulers.computation());
    TestSubscriber<String> ts = new TestSubscriber<String>();
    Observable.zip(o1, o2, new Func2<Integer, Integer, String>() {

        @Override
        public String call(Integer t1, Integer t2) {
            return t1 + "-" + t2;
        }
    }).observeOn(Schedulers.computation()).take(RxRingBuffer.SIZE * 2).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
    System.out.println("Generated => A: " + generatedA.get() + " B: " + generatedB.get());
    assertTrue(generatedA.get() < (RxRingBuffer.SIZE * 4));
    assertTrue(generatedB.get() < (RxRingBuffer.SIZE * 4));
}

17. OperatorZipTest#testDownstreamBackpressureRequestsWithFiniteSyncObservables()

Project: RxJava
File: OperatorZipTest.java
@Test
public void testDownstreamBackpressureRequestsWithFiniteSyncObservables() {
    AtomicInteger generatedA = new AtomicInteger();
    AtomicInteger generatedB = new AtomicInteger();
    Observable<Integer> o1 = createInfiniteObservable(generatedA).take(RxRingBuffer.SIZE * 2);
    Observable<Integer> o2 = createInfiniteObservable(generatedB).take(RxRingBuffer.SIZE * 2);
    TestSubscriber<String> ts = new TestSubscriber<String>();
    Observable.zip(o1, o2, new Func2<Integer, Integer, String>() {

        @Override
        public String call(Integer t1, Integer t2) {
            return t1 + "-" + t2;
        }
    }).observeOn(Schedulers.computation()).take(RxRingBuffer.SIZE * 2).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
    System.out.println("Generated => A: " + generatedA.get() + " B: " + generatedB.get());
    assertTrue(generatedA.get() < (RxRingBuffer.SIZE * 3));
    assertTrue(generatedB.get() < (RxRingBuffer.SIZE * 3));
}

18. OperatorZipTest#testBackpressureAsync()

Project: RxJava
File: OperatorZipTest.java
@Test
public void testBackpressureAsync() {
    AtomicInteger generatedA = new AtomicInteger();
    AtomicInteger generatedB = new AtomicInteger();
    Observable<Integer> o1 = createInfiniteObservable(generatedA).subscribeOn(Schedulers.computation());
    Observable<Integer> o2 = createInfiniteObservable(generatedB).subscribeOn(Schedulers.computation());
    TestSubscriber<String> ts = new TestSubscriber<String>();
    Observable.zip(o1, o2, new Func2<Integer, Integer, String>() {

        @Override
        public String call(Integer t1, Integer t2) {
            return t1 + "-" + t2;
        }
    }).take(RxRingBuffer.SIZE * 2).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
    assertTrue(generatedA.get() < (RxRingBuffer.SIZE * 3));
    assertTrue(generatedB.get() < (RxRingBuffer.SIZE * 3));
}

19. OperatorZipTest#testBackpressureSync()

Project: RxJava
File: OperatorZipTest.java
@Test
public void testBackpressureSync() {
    AtomicInteger generatedA = new AtomicInteger();
    AtomicInteger generatedB = new AtomicInteger();
    Observable<Integer> o1 = createInfiniteObservable(generatedA);
    Observable<Integer> o2 = createInfiniteObservable(generatedB);
    TestSubscriber<String> ts = new TestSubscriber<String>();
    Observable.zip(o1, o2, new Func2<Integer, Integer, String>() {

        @Override
        public String call(Integer t1, Integer t2) {
            return t1 + "-" + t2;
        }
    }).take(RxRingBuffer.SIZE * 2).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    assertEquals(RxRingBuffer.SIZE * 2, ts.getOnNextEvents().size());
    assertTrue(generatedA.get() < (RxRingBuffer.SIZE * 3));
    assertTrue(generatedB.get() < (RxRingBuffer.SIZE * 3));
}

20. QueryTest#testReactivePull()

Project: RxCupboard
File: QueryTest.java
public void testReactivePull() {
    // Normally there are 10 items
    final AtomicInteger allCount = new AtomicInteger();
    rxDatabase.query(TestEntity.class).doOnNext(new Action1<TestEntity>() {

        @Override
        public void call(TestEntity testEntity) {
            allCount.incrementAndGet();
        }
    }).subscribe();
    assertEquals(10, allCount.intValue());
    // Ask for only 5 elements of the 10 in the table
    final AtomicInteger pullCount = new AtomicInteger();
    rxDatabase.query(TestEntity.class).doOnNext(new Action1<TestEntity>() {

        @Override
        public void call(TestEntity testEntity) {
            pullCount.incrementAndGet();
        }
    }).take(5).subscribe();
    assertEquals(5, pullCount.intValue());
}

21. LazyFutureTest#testLazyness()

Project: testcontainers-java
File: LazyFutureTest.java
@Test
public void testLazyness() throws Exception {
    AtomicInteger counter = new AtomicInteger();
    Future<Integer> lazyFuture = new LazyFuture<Integer>() {

        @Override
        protected Integer resolve() {
            return counter.incrementAndGet();
        }
    };
    assertEquals("No resolve() invocations before get()", 0, counter.get());
    assertEquals("get() call returns proper result", 1, lazyFuture.get());
    assertEquals("resolve() was called only once after single get() call", 1, counter.get());
    counter.incrementAndGet();
    assertEquals("result of resolve() must be cached", 1, lazyFuture.get());
}

22. UIHelpers#openOnUIThread()

Project: team-explorer-everywhere
File: UIHelpers.java
public static int openOnUIThread(final Dialog dialog) {
    final AtomicInteger dialogStatus = new AtomicInteger();
    runOnUIThread(false, new Runnable() {

        @Override
        public void run() {
            dialogStatus.set(dialog.open());
        }
    });
    return dialogStatus.get();
}

23. ProxyIp#toVerify()

Project: superword
File: ProxyIp.java
private static List<String> toVerify(Set<String> ips) {
    AtomicInteger i = new AtomicInteger();
    AtomicInteger f = new AtomicInteger();
    List<String> list = ips.parallelStream().filter( ip -> {
        LOGGER.info("?????" + ips.size() + "/" + i.incrementAndGet());
        String[] attr = ip.split(":");
        if (verify(attr[0], Integer.parseInt(attr[1]))) {
            return true;
        }
        IPS.remove(ip);
        f.incrementAndGet();
        return false;
    }).sorted().collect(Collectors.toList());
    LOGGER.info("?????IP??" + (ips.size() - f.get()));
    LOGGER.info("?????IP??" + f.get());
    return list;
}

24. IntStreamExTest#testPeekFirst()

Project: streamex
File: IntStreamExTest.java
@Test
public void testPeekFirst() {
    int[] input = { 1, 10, 100, 1000 };
    AtomicInteger firstElement = new AtomicInteger();
    assertArrayEquals(new int[] { 10, 100, 1000 }, IntStreamEx.of(input).peekFirst(firstElement::set).skip(1).toArray());
    assertEquals(1, firstElement.get());
    assertArrayEquals(new int[] { 10, 100, 1000 }, IntStreamEx.of(input).skip(1).peekFirst(firstElement::set).toArray());
    assertEquals(10, firstElement.get());
    firstElement.set(-1);
    assertArrayEquals(new int[] {}, IntStreamEx.of(input).skip(4).peekFirst(firstElement::set).toArray());
    assertEquals(-1, firstElement.get());
}

25. QueryTest#testAtomicIntegers()

Project: squidb
File: QueryTest.java
public void testAtomicIntegers() {
    AtomicInteger id = new AtomicInteger(1);
    Query query = Query.select(Employee.ID).where(Employee.ID.eq(id));
    SquidCursor<Employee> cursor = database.query(Employee.class, query);
    try {
        assertEquals(1, cursor.getCount());
        cursor.moveToFirst();
        assertEquals(1, cursor.get(Employee.ID).longValue());
    } finally {
        cursor.close();
    }
    id.set(2);
    cursor = database.query(Employee.class, query);
    try {
        assertEquals(1, cursor.getCount());
        cursor.moveToFirst();
        assertEquals(2, cursor.get(Employee.ID).longValue());
    } finally {
        cursor.close();
    }
}

26. AngularObjectTest#testWatcher()

Project: zeppelin
File: AngularObjectTest.java
@Test
public void testWatcher() throws InterruptedException {
    final AtomicInteger updated = new AtomicInteger(0);
    final AtomicInteger onWatch = new AtomicInteger(0);
    AngularObject ao = new AngularObject("name", "value", "note1", null, new AngularObjectListener() {

        @Override
        public void updated(AngularObject updatedObject) {
            updated.incrementAndGet();
        }
    });
    ao.addWatcher(new AngularObjectWatcher(null) {

        @Override
        public void watch(Object oldObject, Object newObject, InterpreterContext context) {
            onWatch.incrementAndGet();
        }
    });
    assertEquals(0, onWatch.get());
    ao.set("newValue");
    Thread.sleep(500);
    assertEquals(1, onWatch.get());
}

27. EHCacheManagerHolder#getCacheManager()

Project: wss4j
File: EHCacheManagerHolder.java
public static CacheManager getCacheManager(String confName, URL configFileURL) {
    CacheManager cacheManager = null;
    if (configFileURL == null) {
        //using the default
        cacheManager = findDefaultCacheManager(confName);
    }
    if (cacheManager == null) {
        if (configFileURL == null) {
            cacheManager = createCacheManager();
        } else {
            cacheManager = findDefaultCacheManager(confName, configFileURL);
        }
    }
    AtomicInteger a = COUNTS.get(cacheManager.getName());
    if (a == null) {
        COUNTS.putIfAbsent(cacheManager.getName(), new AtomicInteger());
        a = COUNTS.get(cacheManager.getName());
    }
    a.incrementAndGet();
    // }
    return cacheManager;
}

28. InlineEnclosureTest#childrenByType()

Project: wicket
File: InlineEnclosureTest.java
private <T> int childrenByType(MarkupContainer parent, Class<T> filter) {
    final AtomicInteger count = new AtomicInteger(0);
    parent.visitChildren(filter, new IVisitor<Component, Void>() {

        @Override
        public void component(Component object, IVisit<Void> visit) {
            count.incrementAndGet();
        }
    });
    return count.get();
}

29. BlockingEventHandlerTest#testMultiple()

Project: reef
File: BlockingEventHandlerTest.java
@Test
public void testMultiple() {
    final AtomicInteger i = new AtomicInteger(0);
    final AtomicInteger cnt = new AtomicInteger(0);
    final BlockingEventHandler<Integer> h = new BlockingEventHandler<>(1, new EventHandler<Iterable<Integer>>() {

        @Override
        public void onNext(final Iterable<Integer> value) {
            for (final int x : value) {
                i.getAndAdd(x);
                cnt.incrementAndGet();
            }
        }
    });
    h.onNext(0xBEEF);
    h.onNext(0xDEAD);
    h.onNext(0xC0FFEE);
    assertEquals(0xBEEF + 0xDEAD + 0xC0FFEE, i.get());
    assertEquals(3, cnt.get());
}

30. BlockingEventHandlerTest#testSingle()

Project: reef
File: BlockingEventHandlerTest.java
@Test
public void testSingle() {
    final AtomicInteger i = new AtomicInteger(0);
    final AtomicInteger cnt = new AtomicInteger(0);
    final BlockingEventHandler<Integer> h = new BlockingEventHandler<>(1, new EventHandler<Iterable<Integer>>() {

        @Override
        public void onNext(final Iterable<Integer> value) {
            for (final int x : value) {
                i.getAndAdd(x);
                cnt.incrementAndGet();
            }
        }
    });
    h.onNext(0xBEEF);
    assertEquals(0xBEEF, i.get());
    assertEquals(1, cnt.get());
}

31. ConnectionPool#initConnections()

Project: redisson
File: ConnectionPool.java
private void initConnections(final ClientConnectionsEntry entry, final Promise<Void> initPromise, boolean checkFreezed) {
    final int minimumIdleSize = getMinimumIdleSize(entry);
    if (minimumIdleSize == 0 || (checkFreezed && entry.isFreezed())) {
        initPromise.setSuccess(null);
        return;
    }
    final AtomicInteger initializedConnections = new AtomicInteger(minimumIdleSize);
    int startAmount = Math.min(50, minimumIdleSize);
    final AtomicInteger requests = new AtomicInteger(startAmount);
    for (int i = 0; i < startAmount; i++) {
        createConnection(checkFreezed, requests, entry, initPromise, minimumIdleSize, initializedConnections);
    }
}

32. FluxTests#testStreamBatchesResults()

Project: reactor-core
File: FluxTests.java
@Test
public void testStreamBatchesResults() {
    Flux<String> stream = Flux.just("1", "2", "3", "4", "5");
    Mono<List<Integer>> s = stream.map(STRING_2_INTEGER).collectList();
    final AtomicInteger batchCount = new AtomicInteger();
    final AtomicInteger count = new AtomicInteger();
    s.subscribe(Subscribers.consumer( is -> {
        batchCount.incrementAndGet();
        for (int i : is) {
            count.addAndGet(i);
        }
    }));
    assertThat("batchCount is 3", batchCount.get(), is(1));
    assertThat("count is 15", count.get(), is(15));
}

33. TestMemoryMessageStore#getMessageCount()

Project: qpid-java
File: TestMemoryMessageStore.java
public int getMessageCount() {
    final AtomicInteger counter = new AtomicInteger();
    newMessageStoreReader().visitMessages(new MessageHandler() {

        @Override
        public boolean handle(StoredMessage<?> storedMessage) {
            counter.incrementAndGet();
            return true;
        }
    });
    return counter.get();
}

34. CommandDefault#next()

Project: isis
File: CommandDefault.java
@Deprecated
@Override
public int next(String sequenceAbbr) {
    AtomicInteger next = sequenceByName.get(sequenceAbbr);
    if (next == null) {
        next = new AtomicInteger(0);
        sequenceByName.put(sequenceAbbr, next);
    } else {
        next.incrementAndGet();
    }
    return next.get();
}

35. RequestQueueTest#testAdd_dedupeByCacheKey()

Project: iosched
File: RequestQueueTest.java
public void testAdd_dedupeByCacheKey() throws Exception {
    OrderCheckingNetwork network = new OrderCheckingNetwork();
    final AtomicInteger parsed = new AtomicInteger();
    final AtomicInteger delivered = new AtomicInteger();
    // Enqueue 2 requests with the same cache key. The first request takes 1.5s. Assert that the
    // second request is only handled after the first one has been parsed and delivered.
    DelayedRequest req1 = new DelayedRequest(1500, parsed, delivered);
    DelayedRequest req2 = new DelayedRequest(0, parsed, delivered) {

        @Override
        protected Response<Object> parseNetworkResponse(NetworkResponse response) {
            // req1 must have been parsed.
            assertEquals(1, parsed.get());
            // req1 must have been parsed.
            assertEquals(1, delivered.get());
            return super.parseNetworkResponse(response);
        }
    };
    network.setExpectedRequests(2);
    RequestQueue queue = new RequestQueue(new NoCache(), network, 3, mDelivery);
    queue.add(req1);
    queue.add(req2);
    queue.start();
    network.waitUntilExpectedDone(2000);
    queue.stop();
}

36. GridTestMessageListener#apply()

Project: ignite
File: GridTestMessageListener.java
/** {@inheritDoc} */
@Override
public boolean apply(UUID nodeId, Object msg) {
    ignite.log().info("Received message [nodeId=" + nodeId + ", locNodeId=" + ignite.cluster().localNode().id() + ", msg=" + msg + ']');
    ConcurrentMap<String, AtomicInteger> map = ignite.cluster().nodeLocalMap();
    AtomicInteger cnt = map.get("msgCnt");
    if (cnt == null) {
        AtomicInteger old = map.putIfAbsent("msgCnt", cnt = new AtomicInteger(0));
        if (old != null)
            cnt = old;
    }
    cnt.incrementAndGet();
    return true;
}

37. AgentInfoSenderTest#agentInfoShouldBeSent()

Project: pinpoint
File: AgentInfoSenderTest.java
@Test
public void agentInfoShouldBeSent() throws InterruptedException {
    final AtomicInteger requestCount = new AtomicInteger();
    final AtomicInteger successCount = new AtomicInteger();
    final long agentInfoSendRetryIntervalMs = 100L;
    ResponseServerMessageListener serverListener = new ResponseServerMessageListener(requestCount, successCount);
    PinpointServerAcceptor serverAcceptor = createServerAcceptor(serverListener);
    PinpointClientFactory clientFactory = createPinpointClientFactory();
    PinpointClient pinpointClient = ClientFactoryUtils.createPinpointClient(HOST, PORT, clientFactory);
    TcpDataSender dataSender = new TcpDataSender(pinpointClient);
    AgentInfoSender agentInfoSender = new AgentInfoSender.Builder(dataSender, getAgentInfo()).sendInterval(agentInfoSendRetryIntervalMs).build();
    try {
        agentInfoSender.start();
        waitExpectedRequestCount(requestCount, 1);
    } finally {
        closeAll(serverAcceptor, agentInfoSender, pinpointClient, clientFactory);
    }
    assertEquals(1, requestCount.get());
    assertEquals(1, successCount.get());
}

38. TestContinuations#testOnSuccessNotCalledWhenException()

Project: parseq
File: TestContinuations.java
@Test
public void testOnSuccessNotCalledWhenException() {
    final AtomicInteger sequence = new AtomicInteger(0);
    final AtomicInteger onSuccess = new AtomicInteger();
    Continuations CONT = new Continuations();
    try {
        CONT.submit(() -> {
            throw new RuntimeException("test");
        });
        CONT.submit(() -> {
            onSuccess.set(sequence.incrementAndGet());
        });
        fail("should have thrown exception");
    } catch (Exception e) {
        assertEquals(e.getMessage(), "test");
    }
    assertEquals(onSuccess.get(), 0);
}

39. OAbstractProfiler#reportTip()

Project: orientdb
File: OAbstractProfiler.java
public int reportTip(final String iMessage) {
    AtomicInteger counter = getTip(iMessage);
    if (counter == null) {
        // DUMP THE MESSAGE ONLY THE FIRST TIME
        OLogManager.instance().info(this, "[TIP] " + iMessage);
        counter = new AtomicInteger(0);
    }
    setTip(iMessage, counter);
    return counter.incrementAndGet();
}

40. FlatMapOpTest#testClose()

Project: openjdk
File: FlatMapOpTest.java
@Test
public void testClose() {
    AtomicInteger before = new AtomicInteger();
    AtomicInteger onClose = new AtomicInteger();
    Supplier<Stream<Integer>> s = () -> {
        before.set(0);
        onClose.set(0);
        return Stream.of(1, 2).peek( e -> before.getAndIncrement());
    };
    s.get().flatMap( i -> Stream.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToInt( i -> IntStream.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToLong( i -> LongStream.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
    s.get().flatMapToDouble( i -> DoubleStream.of(i, i).onClose(onClose::getAndIncrement)).count();
    assertEquals(before.get(), onClose.get());
}

41. GridNioSessionMetaKeySelfTest#testNextRandomKey()

Project: ignite
File: GridNioSessionMetaKeySelfTest.java
/**
     * @throws Exception If failed.
     */
public void testNextRandomKey() throws Exception {
    AtomicInteger keyGen = U.staticField(GridNioSessionMetaKey.class, "keyGen");
    int initVal = keyGen.get();
    int key = GridNioSessionMetaKey.nextUniqueKey();
    // Check key is greater than any real GridNioSessionMetaKey ordinal.
    assertTrue(key >= GridNioSessionMetaKey.values().length);
    // Check all valid and some invalid key values.
    for (int i = ++key; i < GridNioSessionMetaKey.MAX_KEYS_CNT + 10; i++) {
        if (i < GridNioSessionMetaKey.MAX_KEYS_CNT)
            assertEquals(i, GridNioSessionMetaKey.nextUniqueKey());
        else
            GridTestUtils.assertThrows(log, new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    return GridNioSessionMetaKey.nextUniqueKey();
                }
            }, IllegalStateException.class, "Maximum count of NIO session keys in system is limited by");
    }
    keyGen.set(initVal);
}

42. DummyService#execute()

Project: ignite
File: DummyService.java
/** {@inheritDoc} */
@Override
public void execute(ServiceContext ctx) {
    AtomicInteger cntr = started.get(ctx.name());
    if (cntr == null) {
        AtomicInteger old = started.putIfAbsent(ctx.name(), cntr = new AtomicInteger());
        if (old != null)
            cntr = old;
    }
    cntr.incrementAndGet();
    System.out.println("Executing service: " + ctx.name());
    CountDownLatch latch = exeLatches.get(ctx.name());
    if (latch != null)
        latch.countDown();
}

43. DummyService#init()

Project: ignite
File: DummyService.java
/** {@inheritDoc} */
@Override
public void init(ServiceContext ctx) throws Exception {
    AtomicInteger cntr = inited.get(ctx.name());
    if (cntr == null) {
        AtomicInteger old = inited.putIfAbsent(ctx.name(), cntr = new AtomicInteger());
        if (old != null)
            cntr = old;
    }
    cntr.incrementAndGet();
    System.out.println("Initializing service: " + ctx.name());
}

44. DummyService#cancel()

Project: ignite
File: DummyService.java
/** {@inheritDoc} */
@Override
public void cancel(ServiceContext ctx) {
    AtomicInteger cntr = cancelled.get(ctx.name());
    if (cntr == null) {
        AtomicInteger old = cancelled.putIfAbsent(ctx.name(), cntr = new AtomicInteger());
        if (old != null)
            cntr = old;
    }
    cntr.incrementAndGet();
    CountDownLatch latch = cancelLatches.get(ctx.name());
    if (latch != null)
        latch.countDown();
    System.out.println("Cancelling service: " + ctx.name());
}

45. GridCacheRebalancingSyncSelfTest#checkPartitionMapMessagesAbsent()

Project: ignite
File: GridCacheRebalancingSyncSelfTest.java
/**
     * @throws Exception If failed.
     */
protected void checkPartitionMapMessagesAbsent() throws Exception {
    map.clear();
    record = true;
    U.sleep(30_000);
    record = false;
    AtomicInteger iF = map.get(GridDhtPartitionsFullMessage.class);
    AtomicInteger iS = map.get(GridDhtPartitionsSingleMessage.class);
    Integer fullMap = iF != null ? iF.get() : null;
    Integer singleMap = iS != null ? iS.get() : null;
    // 1 message can be sent right after all checks passed.
    assertTrue("Unexpected full map messages: " + fullMap, fullMap == null || fullMap.equals(1));
    assertNull("Unexpected single map messages", singleMap);
}

46. DataPointsMonitor#addCounter()

Project: kairosdb
File: DataPointsMonitor.java
private void addCounter(String name, int count) {
    AtomicInteger ai = m_metricCounters.get(name);
    if (ai == null) {
        ai = new AtomicInteger();
        AtomicInteger mapValue = m_metricCounters.putIfAbsent(name, ai);
        //This handles the case if one snuck in on another thread.
        ai = (mapValue != null ? mapValue : ai);
    }
    ai.addAndGet(count);
}

47. MPerf#sendMessages()

Project: JGroups
File: MPerf.java
protected void sendMessages() {
    // all threads will increment this
    final AtomicInteger num_msgs_sent = new AtomicInteger(0);
    // incremented *after* sending a message
    final AtomicInteger actually_sent = new AtomicInteger(0);
    // monotonically increasing seqno, to be used by all threads
    final AtomicLong seqno = new AtomicLong(1);
    final Sender[] senders = new Sender[num_threads];
    final CyclicBarrier barrier = new CyclicBarrier(num_threads + 1);
    final byte[] payload = new byte[msg_size];
    for (int i = 0; i < num_threads; i++) {
        senders[i] = new Sender(barrier, num_msgs_sent, actually_sent, seqno, payload);
        senders[i].setName("sender-" + i);
        senders[i].start();
    }
    try {
        System.out.println("-- sending " + num_msgs + (oob ? " OOB msgs" : " msgs"));
        barrier.await();
    } catch (Exception e) {
        System.err.println("failed triggering send threads: " + e);
    }
}

48. SinglePromiseTest#testFailWait()

Project: jdeferred
File: SinglePromiseTest.java
@Test
public void testFailWait() {
    final AtomicInteger failCount = new AtomicInteger();
    final AtomicInteger doneCount = new AtomicInteger();
    deferredManager.when(failedCallable(new RuntimeException("oops"), 1000)).done(new DoneCallback() {

        public void onDone(Object result) {
            doneCount.incrementAndGet();
        }
    }).fail(new FailCallback() {

        public void onFail(Object result) {
            failCount.incrementAndGet();
        }
    });
    waitForCompletion();
    Assert.assertEquals(0, doneCount.get());
    Assert.assertEquals(1, failCount.get());
}

49. CompactionRequest#getCompactionState()

Project: hindex
File: CompactionRequest.java
/**
     * Find out if a given region in compaction now.
     *
     * @param regionId
     * @return
     */
public static CompactionState getCompactionState(final long regionId) {
    Long key = Long.valueOf(regionId);
    AtomicInteger major = majorCompactions.get(key);
    AtomicInteger minor = minorCompactions.get(key);
    int state = 0;
    if (minor != null && minor.get() > 0) {
        // use 1 to indicate minor here
        state += 1;
    }
    if (major != null && major.get() > 0) {
        // use 2 to indicate major here
        state += 2;
    }
    switch(state) {
        case // 3 = 2 + 1, so both major and minor
        3:
            return CompactionState.MAJOR_AND_MINOR;
        case 2:
            return CompactionState.MAJOR;
        case 1:
            return CompactionState.MINOR;
        default:
            return CompactionState.NONE;
    }
}

50. IndexManager#incrementRegionCount()

Project: hindex
File: IndexManager.java
public void incrementRegionCount(String tableName) {
    AtomicInteger count = this.tableVsNumberOfRegions.get(tableName);
    // initialized
    if (null == count) {
        synchronized (tableVsNumberOfRegions) {
            count = this.tableVsNumberOfRegions.get(tableName);
            if (null == count) {
                count = new AtomicInteger(0);
                this.tableVsNumberOfRegions.put(tableName, count);
            }
        }
    }
    count.incrementAndGet();
}

51. SpoutInstanceTest#after()

Project: heron
File: SpoutInstanceTest.java
@After
public void after() throws Exception {
    UnitTestHelper.clearSingletonRegistry();
    slaveLooper.exitLoop();
    testLooper.exitLoop();
    tupleReceived = 0;
    heronDataTupleList = new ArrayList<HeronTuples.HeronDataTuple>();
    ackCount = new AtomicInteger(0);
    failCount = new AtomicInteger(0);
    threadsPool.shutdownNow();
    physicalPlan = null;
    testLooper = null;
    slaveLooper = null;
    outStreamQueue = null;
    inStreamQueue = null;
    slave = null;
    threadsPool = null;
}

52. SpoutInstanceTest#before()

Project: heron
File: SpoutInstanceTest.java
@Before
public void before() throws Exception {
    UnitTestHelper.addSystemConfigToSingleton();
    tupleReceived = 0;
    heronDataTupleList = new ArrayList<HeronTuples.HeronDataTuple>();
    ackCount = new AtomicInteger(0);
    failCount = new AtomicInteger(0);
    testLooper = new SlaveLooper();
    slaveLooper = new SlaveLooper();
    outStreamQueue = new Communicator<HeronTuples.HeronTupleSet>(slaveLooper, testLooper);
    outStreamQueue.init(Constants.QUEUE_BUFFER_SIZE, Constants.QUEUE_BUFFER_SIZE, 0.5);
    inStreamQueue = new Communicator<HeronTuples.HeronTupleSet>(testLooper, slaveLooper);
    inStreamQueue.init(Constants.QUEUE_BUFFER_SIZE, Constants.QUEUE_BUFFER_SIZE, 0.5);
    slaveMetricsOut = new Communicator<Metrics.MetricPublisherPublishMessage>(slaveLooper, testLooper);
    slaveMetricsOut.init(Constants.QUEUE_BUFFER_SIZE, Constants.QUEUE_BUFFER_SIZE, 0.5);
    inControlQueue = new Communicator<InstanceControlMsg>(testLooper, slaveLooper);
    slave = new Slave(slaveLooper, inStreamQueue, outStreamQueue, inControlQueue, slaveMetricsOut);
    threadsPool = Executors.newSingleThreadExecutor();
    threadsPool.execute(slave);
}

53. ElementsTest#testModulesAreInstalledAtMostOnce()

Project: guice
File: ElementsTest.java
// Business logic tests
public void testModulesAreInstalledAtMostOnce() {
    final AtomicInteger aConfigureCount = new AtomicInteger(0);
    final Module a = new AbstractModule() {

        public void configure() {
            aConfigureCount.incrementAndGet();
        }
    };
    Elements.getElements(a, a);
    assertEquals(1, aConfigureCount.get());
    aConfigureCount.set(0);
    Module b = new AbstractModule() {

        protected void configure() {
            install(a);
            install(a);
        }
    };
    Elements.getElements(b);
    assertEquals(1, aConfigureCount.get());
}

54. ParallelIterate2Test#creationAndExecution()

Project: eclipse-collections
File: ParallelIterate2Test.java
/**
     * crude test to check that creation works and that all tasks are executed
     */
@Test
public void creationAndExecution() throws InterruptedException {
    int howManyTimes = 200;
    AtomicInteger counter = new AtomicInteger(0);
    Collection<Callable<Integer>> tasks = new ArrayList<>();
    Interval.oneTo(howManyTimes).run(() -> tasks.add(counter::getAndIncrement));
    ExecutorService executorService1 = ParallelIterate.newPooledExecutor(4, "test pool 2 4", true);
    executorService1.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
    counter.set(0);
    ExecutorService executorService2 = ParallelIterate.newPooledExecutor(2, "test pool 2", true);
    executorService2.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
}

55. TestMarshallingUtilsTest#testCompareAtomicPrimitives()

Project: drools
File: TestMarshallingUtilsTest.java
@Test
@Ignore
public void testCompareAtomicPrimitives() {
    AtomicInteger objA = new AtomicInteger(-1);
    AtomicInteger objB = new AtomicInteger(-1);
    int a = objA.get();
    int b = objB.get();
    assertFalse("objs?", objA.equals(objB));
    assertTrue("ints?", a == b);
    assertTrue("compare a?", CompareViaReflectionUtil.compareAtomicPrimitives(objA, objB));
    AtomicBoolean objC = new AtomicBoolean(false);
    AtomicBoolean objD = new AtomicBoolean(false);
    boolean c = objC.get();
    boolean d = objD.get();
    assertFalse("objs?", objC.equals(objD));
    assertTrue("bools?", c == d);
    assertTrue("compare c?", CompareViaReflectionUtil.compareAtomicPrimitives(objC, objD));
}

56. ReflectionObfuscationTransformer#findReflectionObfuscation()

Project: deobfuscator
File: ReflectionObfuscationTransformer.java
public int findReflectionObfuscation() throws Throwable {
    AtomicInteger count = new AtomicInteger(0);
    classNodes().stream().map(WrappedClassNode::getClassNode).forEach( classNode -> {
        classNode.methods.forEach( methodNode -> {
            for (int i = 0; i < methodNode.instructions.size(); i++) {
                AbstractInsnNode current = methodNode.instructions.get(i);
                if (current instanceof MethodInsnNode) {
                    MethodInsnNode methodInsnNode = (MethodInsnNode) current;
                    if (methodInsnNode.desc.equals("(J)Ljava/lang/reflect/Method;") || methodInsnNode.desc.equals("(J)Ljava/lang/reflect/Field;")) {
                        count.incrementAndGet();
                    }
                }
            }
        });
    });
    return count.get();
}

57. TypesMatchTest#testMethodLocalMaskingTypesMatch()

Project: android-retrolambda-lombok
File: TypesMatchTest.java
@Test
public void testMethodLocalMaskingTypesMatch() {
    Source s = new Source(METHOD_LOCAL_MASKING_SOURCE, "MaskingTypesMatchTest.java");
    s.parseCompilationUnit();
    final AtomicInteger hit1 = new AtomicInteger();
    final AtomicInteger hit2 = new AtomicInteger();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitVariableDefinitionEntry(VariableDefinitionEntry node) {
            if ("thisIsAUtilList".equals(node.astName().astValue())) {
                assertTrue("thisIsAUtilList isn't matched to java.util.List, but should.", new Resolver().typesMatch("java.util.List<?>", node.upToVariableDefinition().astTypeReference()));
                hit1.incrementAndGet();
            }
            if ("butThisIsnt".equals(node.astName().astValue())) {
                assertFalse("butThisIsnt is matched to java.util.List, but shouldn't be.", new Resolver().typesMatch("java.util.List<?>", node.upToVariableDefinition().astTypeReference()));
                hit2.incrementAndGet();
            }
            return true;
        }
    });
    assertEquals("expected 1 hit on VarDefEntry 'thisIsAUtilList'", 1, hit1.get());
    assertEquals("expected 1 hit on VarDefEntry 'butThisIsnt'", 1, hit2.get());
}

58. TestAsyncSemaphore#testMultiThreadBoundedConcurrency()

Project: airlift
File: TestAsyncSemaphore.java
@Test
public void testMultiThreadBoundedConcurrency() throws Exception {
    AsyncSemaphore<Runnable> asyncSemaphore = new AsyncSemaphore<>(2, executor, executor::submit);
    AtomicInteger count = new AtomicInteger();
    AtomicInteger concurrency = new AtomicInteger();
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        futures.add(asyncSemaphore.submit(() -> {
            count.incrementAndGet();
            int currentConcurrency = concurrency.incrementAndGet();
            assertLessThanOrEqual(currentConcurrency, 2);
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
            concurrency.decrementAndGet();
        }));
    }
    // Wait for completion
    Futures.allAsList(futures).get(1, TimeUnit.MINUTES);
    Assert.assertEquals(count.get(), 1000);
}

59. TestAsyncSemaphore#testSingleThreadBoundedConcurrency()

Project: airlift
File: TestAsyncSemaphore.java
@Test
public void testSingleThreadBoundedConcurrency() throws Exception {
    AsyncSemaphore<Runnable> asyncSemaphore = new AsyncSemaphore<>(1, executor, executor::submit);
    AtomicInteger count = new AtomicInteger();
    AtomicInteger concurrency = new AtomicInteger();
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        futures.add(asyncSemaphore.submit((Runnable) () -> {
            count.incrementAndGet();
            int currentConcurrency = concurrency.incrementAndGet();
            assertLessThanOrEqual(currentConcurrency, 1);
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
            concurrency.decrementAndGet();
        }));
    }
    // Wait for completion
    Futures.allAsList(futures).get(1, TimeUnit.MINUTES);
    Assert.assertEquals(count.get(), 1000);
}

60. ParallelIterate2Test#creationAndExecution()

Project: gs-collections
File: ParallelIterate2Test.java
/**
     * crude test to check that creation works and that all tasks are executed
     */
@Test
public void creationAndExecution() throws InterruptedException {
    int howManyTimes = 200;
    AtomicInteger counter = new AtomicInteger(0);
    Collection<Callable<Integer>> tasks = new ArrayList<>();
    Interval.oneTo(howManyTimes).run(() -> tasks.add(counter::getAndIncrement));
    ExecutorService executorService1 = ParallelIterate.newPooledExecutor(4, "test pool 2 4", true);
    executorService1.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
    counter.set(0);
    ExecutorService executorService2 = ParallelIterate.newPooledExecutor(2, "test pool 2", true);
    executorService2.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
}

61. SparkTransactionServiceTest#testExplicitTransaction()

Project: cdap
File: SparkTransactionServiceTest.java
/**
   * Tests the explicit transaction that covers multiple jobs.
   */
@Test
public void testExplicitTransaction() throws Exception {
    final AtomicInteger jobIdGen = new AtomicInteger();
    final AtomicInteger stageIdGen = new AtomicInteger();
    Transaction transaction = txClient.startLong();
    // Execute two jobs with the same explicit transaction
    testRunJob(jobIdGen.getAndIncrement(), generateStages(stageIdGen, 2), true, transaction);
    testRunJob(jobIdGen.getAndIncrement(), generateStages(stageIdGen, 3), true, transaction);
    // Should be able to commit the transaction
    Assert.assertTrue(txClient.commit(transaction));
}

62. SingleConsumerQueueTest#oneProducer_oneConsumer()

Project: caffeine
File: SingleConsumerQueueTest.java
/* ---------------- Concurrency -------------- */
@Test(dataProvider = "empty")
public void oneProducer_oneConsumer(Queue<Integer> queue) {
    AtomicInteger started = new AtomicInteger();
    AtomicInteger finished = new AtomicInteger();
    ConcurrentTestHarness.execute(() -> {
        started.incrementAndGet();
        Awaits.await().untilAtomic(started, is(2));
        for (int i = 0; i < PRODUCE; i++) {
            queue.add(i);
        }
        finished.incrementAndGet();
    });
    ConcurrentTestHarness.execute(() -> {
        started.incrementAndGet();
        Awaits.await().untilAtomic(started, is(2));
        for (int i = 0; i < PRODUCE; i++) {
            while (queue.poll() == null) {
            }
        }
        finished.incrementAndGet();
    });
    Awaits.await().untilAtomic(finished, is(2));
    assertThat(queue, is(deeplyEmpty()));
}

63. WriteBufferTest#oneProducer_oneConsumer()

Project: caffeine
File: WriteBufferTest.java
/* ---------------- Concurrency -------------- */
@Test(dataProvider = "empty")
public void oneProducer_oneConsumer(WriteBuffer<Integer> buffer) {
    AtomicInteger started = new AtomicInteger();
    AtomicInteger finished = new AtomicInteger();
    ConcurrentTestHarness.execute(() -> {
        started.incrementAndGet();
        Awaits.await().untilAtomic(started, is(2));
        for (int i = 0; i < PRODUCE; i++) {
            while (!buffer.offer(i)) {
            }
        }
        finished.incrementAndGet();
    });
    ConcurrentTestHarness.execute(() -> {
        started.incrementAndGet();
        Awaits.await().untilAtomic(started, is(2));
        for (int i = 0; i < PRODUCE; i++) {
            while (buffer.poll() == null) {
            }
        }
        finished.incrementAndGet();
    });
    Awaits.await().untilAtomic(finished, is(2));
    assertThat(buffer.size(), is(0));
}

64. ReflectionObfuscationTransformer#count()

Project: deobfuscator
File: ReflectionObfuscationTransformer.java
private int count() {
    AtomicInteger total = new AtomicInteger();
    classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> {
        classNode.methods.forEach( methodNode -> {
            for (int i = 0; i < methodNode.instructions.size(); i++) {
                AbstractInsnNode abstractInsnNode = methodNode.instructions.get(i);
                if (abstractInsnNode instanceof MethodInsnNode) {
                    MethodInsnNode methodInsnNode = (MethodInsnNode) abstractInsnNode;
                    WrappedClassNode wrappedTarget = classpath.get(methodInsnNode.owner);
                    if (wrappedTarget != null) {
                        ClassNode target = wrappedTarget.getClassNode();
                        MethodNode method = target.methods.stream().filter( mn -> mn.name.equals(methodInsnNode.name) && mn.desc.equals(methodInsnNode.desc)).findFirst().orElse(null);
                        if (method != null) {
                            if (isValidTarget(target, method)) {
                                total.incrementAndGet();
                            }
                        }
                    }
                }
            }
        });
    });
    return total.get();
}

65. InvokedynamicTransformer#cleanup()

Project: deobfuscator
File: InvokedynamicTransformer.java
private int cleanup() {
    AtomicInteger total = new AtomicInteger();
    classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> {
        Iterator<MethodNode> it = classNode.methods.iterator();
        while (it.hasNext()) {
            MethodNode node = it.next();
            if (node.desc.equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;)Ljava/lang/Object;")) {
                it.remove();
                total.incrementAndGet();
            }
        }
    });
    return total.get();
}

66. InvokedynamicTransformer#findInvokeDynamic()

Project: deobfuscator
File: InvokedynamicTransformer.java
private int findInvokeDynamic() {
    AtomicInteger total = new AtomicInteger();
    classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> {
        classNode.methods.forEach( methodNode -> {
            for (int i = 0; i < methodNode.instructions.size(); i++) {
                AbstractInsnNode abstractInsnNode = methodNode.instructions.get(i);
                if (abstractInsnNode instanceof InvokeDynamicInsnNode) {
                    InvokeDynamicInsnNode dyn = (InvokeDynamicInsnNode) abstractInsnNode;
                    if (dyn.bsmArgs[0] instanceof String) {
                        total.incrementAndGet();
                    }
                }
            }
        });
    });
    return total.get();
}

67. SetBindingTest#multiValueBindings_WithSingletonsAcrossMultipleInjectableTypes()

Project: dagger
File: SetBindingTest.java
@Test
public void multiValueBindings_WithSingletonsAcrossMultipleInjectableTypes() {
    final AtomicInteger singletonCounter = new AtomicInteger(100);
    final AtomicInteger defaultCounter = new AtomicInteger(200);
    class TestEntryPoint1 {

        @Inject
        Set<Integer> objects1;
    }
    class TestEntryPoint2 {

        @Inject
        Set<Integer> objects2;
    }
    @Module(injects = { TestEntryPoint1.class, TestEntryPoint2.class })
    class TestModule {

        @Provides(type = SET)
        @Singleton
        Integer a() {
            return singletonCounter.getAndIncrement();
        }

        @Provides(type = SET)
        Integer b() {
            return defaultCounter.getAndIncrement();
        }
    }
    ObjectGraph graph = ObjectGraph.createWith(new TestingLoader(), new TestModule());
    TestEntryPoint1 ep1 = graph.inject(new TestEntryPoint1());
    TestEntryPoint2 ep2 = graph.inject(new TestEntryPoint2());
    assertEquals(set(100, 200), ep1.objects1);
    assertEquals(set(100, 201), ep2.objects2);
}

68. SetBindingTest#multiValueBindings_WithSingletonAndDefaultValues()

Project: dagger
File: SetBindingTest.java
@Test
public void multiValueBindings_WithSingletonAndDefaultValues() {
    final AtomicInteger singletonCounter = new AtomicInteger(100);
    final AtomicInteger defaultCounter = new AtomicInteger(200);
    class TestEntryPoint {

        @Inject
        Set<Integer> objects1;

        @Inject
        Set<Integer> objects2;
    }
    @Module(injects = TestEntryPoint.class)
    class TestModule {

        @Provides(type = SET)
        @Singleton
        Integer a() {
            return singletonCounter.getAndIncrement();
        }

        @Provides(type = SET)
        Integer b() {
            return defaultCounter.getAndIncrement();
        }
    }
    TestEntryPoint ep = injectWithModule(new TestEntryPoint(), new TestModule());
    assertEquals(set(100, 200), ep.objects1);
    assertEquals(set(100, 201), ep.objects2);
}

69. AutoclosingTest#autoClosingZip()

Project: cyclops-react
File: AutoclosingTest.java
@Test
public void autoClosingZip() throws InterruptedException {
    System.out.println("Started!");
    close = new AtomicInteger();
    added = new AtomicInteger();
    //subscription fills from outside in (right to left), need to store open / closed for each queue
    List<Tuple2<List<List<String>>, Integer>> results = new LazyReact().generateAsync(() -> nextValues()).withQueueFactory(() -> eventQueue()).zip(LazyFutureStream.parallel(1, 2, 3)).collect(Collectors.toList());
    System.out.println("finished");
    int localAdded = added.get();
    assertThat(close.get(), greaterThan(0));
    assertThat(results.size(), is(3));
    assertThat(localAdded, is(added.get()));
}

70. AutoclosingTest#autoClosingLimit1()

Project: cyclops-react
File: AutoclosingTest.java
@Test
public void autoClosingLimit1() throws InterruptedException {
    close = new AtomicInteger();
    added = new AtomicInteger();
    //subscription fills from outside in (right to left), need to store open / closed for each queue
    List<String> results = new LazyReact().generateAsync(() -> nextValues()).withQueueFactory(() -> eventQueue()).flatMap( list -> list.stream()).peek(System.out::println).flatMap( list -> list.stream()).peek(System.out::println).limit(1).collect(Collectors.toList());
    System.out.println("finished");
    int localAdded = added.get();
    assertThat(close.get(), greaterThan(0));
    assertThat(results.size(), is(1));
    assertThat(localAdded, is(added.get()));
}

71. NormalizedNodePrunerTest#countNodes()

Project: controller
File: NormalizedNodePrunerTest.java
private static int countNodes(NormalizedNode<?, ?> normalizedNode, final String namespaceFilter) {
    if (normalizedNode == null) {
        return 0;
    }
    final AtomicInteger count = new AtomicInteger();
    new NormalizedNodeNavigator(( level,  parentPath,  normalizedNode1) -> {
        if (!(normalizedNode1.getIdentifier() instanceof AugmentationIdentifier)) {
            if (normalizedNode1.getIdentifier().getNodeType().getNamespace().toString().contains(namespaceFilter)) {
                count.incrementAndGet();
            }
        }
    }).navigate(YangInstanceIdentifier.EMPTY.toString(), normalizedNode);
    return count.get();
}

72. JgroupsConnectorTest_Gossip#testConnectorRecoversWhenGossipRouterReconnects()

Project: AxonFramework
File: JgroupsConnectorTest_Gossip.java
@Test
public void testConnectorRecoversWhenGossipRouterReconnects() throws Exception {
    final AtomicInteger counter1 = new AtomicInteger(0);
    final AtomicInteger counter2 = new AtomicInteger(0);
    connector1.subscribe(String.class.getName(), new CountingCommandHandler(counter1));
    connector1.connect(20);
    assertTrue("Expected connector 1 to connect within 10 seconds", connector1.awaitJoined(10, TimeUnit.SECONDS));
    connector2.subscribe(Long.class.getName(), new CountingCommandHandler(counter2));
    connector2.connect(80);
    assertTrue("Connector 2 failed to connect", connector2.awaitJoined());
    // the nodes joined, but didn't detect eachother
    gossipRouter.start();
    // now, they should detect eachother and start syncing their state
    waitForConnectorSync(60);
}

73. JGroupsConnectorTest#testJoinMessageReceivedForDisconnectedHost()

Project: AxonFramework
File: JGroupsConnectorTest.java
@Test
public void testJoinMessageReceivedForDisconnectedHost() throws Exception {
    final AtomicInteger counter1 = new AtomicInteger(0);
    final AtomicInteger counter2 = new AtomicInteger(0);
    connector1.subscribe(String.class.getName(), new CountingCommandHandler(counter1));
    connector1.connect(20);
    assertTrue("Expected connector 1 to connect within 10 seconds", connector1.awaitJoined(10, TimeUnit.SECONDS));
    connector2.subscribe(String.class.getName(), new CountingCommandHandler(counter2));
    connector2.connect(80);
    assertTrue("Connector 2 failed to connect", connector2.awaitJoined());
    // wait for both connectors to have the same view
    waitForConnectorSync();
    ConsistentHash hashBefore = connector1.getConsistentHash();
    // secretly insert an illegal message
    channel1.getReceiver().receive(new Message(channel1.getAddress(), new IpAddress(12345), new JoinMessage(10, Collections.<String>emptySet())));
    ConsistentHash hash2After = connector1.getConsistentHash();
    assertEquals("That message should not have changed the ring", hashBefore, hash2After);
}

74. EventCountSnapshotterTrigger#decorateForAppend()

Project: AxonFramework
File: EventCountSnapshotterTrigger.java
@Override
public List<DomainEventMessage<?>> decorateForAppend(Aggregate<?> aggregate, List<DomainEventMessage<?>> eventStream) {
    String aggregateIdentifier = aggregate.identifier();
    counters.putIfAbsent(aggregateIdentifier, new AtomicInteger(0));
    AtomicInteger counter = counters.get(aggregateIdentifier);
    counter.addAndGet(eventStream.size());
    if (counter.get() > trigger) {
        CurrentUnitOfWork.get().onCleanup( u -> triggerSnapshotIfRequired(aggregate.rootType(), aggregateIdentifier, counter));
    }
    return eventStream;
}

75. HttpClientVertxTest#connect()

Project: qbit
File: HttpClientVertxTest.java
public void connect() {
    port = PortUtils.findOpenPortStartAt(port);
    server = new HttpServerBuilder().setPort(port).build();
    client = new HttpClientBuilder().setPoolSize(1).setPort(port).build();
    requestReceived = new AtomicBoolean();
    responseReceived = new AtomicBoolean();
    messageBody = new AtomicReference<>();
    responseCode = new AtomicInteger();
    port++;
}

76. RoundRobinServiceDispatcherTest#testWithReturn()

Project: qbit
File: RoundRobinServiceDispatcherTest.java
@Test
public void testWithReturn() {
    final MultiWorkerClient worker = bundle.createLocalProxy(MultiWorkerClient.class, "/workers");
    final AtomicInteger callbackCounter = new AtomicInteger();
    for (int index = 0; index < 200; index++) {
        worker.doSomeWork2( integer -> callbackCounter.incrementAndGet());
    }
    ServiceProxyUtils.flushServiceProxy(worker);
    super.waitForTrigger(30,  o -> callbackCounter.get() >= 200);
    assertEquals(200, callbackCounter.get());
}

77. ServiceImplTest#testServiceCallback()

Project: qbit
File: ServiceImplTest.java
@Test
public void testServiceCallback() throws Exception {
    QBit.factory().systemEventManager();
    AtomicReference<String> returnString = new AtomicReference<>();
    serviceQueue.startCallBackHandler();
    Sys.sleep(100);
    AtomicInteger returnValue = new AtomicInteger();
    proxy.methodWithCallBack( s -> returnString.set(s), "hello");
    proxy.clientProxyFlush();
    Sys.sleep(1000);
    ok = callCount == 1 || die();
    ok = returnString.get().equals("hello") || die();
}

78. ServiceImplTest#testCallback()

Project: qbit
File: ServiceImplTest.java
@Test
public void testCallback() throws Exception {
    serviceQueue.startCallBackHandler();
    Sys.sleep(100);
    AtomicInteger returnValue = new AtomicInteger();
    proxy.method2( integer -> {
        returnValue.set(integer);
    });
    proxy.clientProxyFlush();
    Sys.sleep(1000);
    ok = callCount == 1 || die();
    ok = returnValue.get() == 1 || die(returnValue.get());
}

79. ServiceBundleImplTest#testCallback()

Project: qbit
File: ServiceBundleImplTest.java
@Test
public void testCallback() throws Exception {
    serviceBundle.addService(new MockService());
    proxy = serviceBundle.createLocalProxy(MockServiceInterface.class, "mockService");
    serviceBundle.startReturnHandlerProcessor();
    AtomicInteger returnValue = new AtomicInteger();
    proxy.method2( integer -> {
        returnValue.set(integer);
    });
    proxy.clientProxyFlush();
    Sys.sleep(1000);
    ok = callCount == 1 || die();
    ok = returnValue.get() == 1 || die(returnValue.get());
}

80. ServiceWorkersTest#setup()

Project: qbit
File: ServiceWorkersTest.java
@Before
public void setup() {
    systemManager = new QBitSystemManager();
    myServiceList = new ArrayList<>(numServices);
    for (int index = 0; index < numServices; index++) {
        myServiceList.add(new MyService());
    }
    final AtomicInteger serviceCount = new AtomicInteger();
    serviceBundleBuilder = ServiceBundleBuilder.serviceBundleBuilder().setSystemManager(systemManager);
    serviceBundle = serviceBundleBuilder.build();
    serviceBundle.addRoundRobinService("/myService", numServices, () -> myServiceList.get(serviceCount.getAndIncrement()));
    serviceBundle.start();
    myService = serviceBundle.createLocalProxy(IMyService.class, "/myService");
}

81. BoonClientIntegrationTest#setUp()

Project: qbit
File: BoonClientIntegrationTest.java
@Before
public void setUp() throws Exception {
    setupLatch();
    sum = new AtomicInteger();
    client = new BoonClientFactory().create("/services", new HttpClientMock(), 10, new BeforeMethodSent() {
    });
    client.start();
    serviceBundle = new ServiceBundleBuilder().setAddress("/services").buildAndStart();
    serviceBundle.addService(new ServiceMock());
    sum.set(0);
    serviceBundle.startReturnHandlerProcessor( item -> response = item);
    Sys.sleep(1000);
}

82. TestCustomizedTPE#testExecutor()

Project: Priam
File: TestCustomizedTPE.java
@Test
public void testExecutor() throws InterruptedException {
    final AtomicInteger count = new AtomicInteger();
    for (int i = 0; i < 100; i++) {
        startTest.submit(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                Thread.sleep(100);
                logger.info("Count:" + count.incrementAndGet());
                return null;
            }
        });
    }
    startTest.sleepTillEmpty();
    assertEquals(100, count.get());
}

83. SideEffectFunctionPipeTest#testPipeBasic()

Project: pipes
File: SideEffectFunctionPipeTest.java
public void testPipeBasic() {
    AtomicInteger count = new AtomicInteger(0);
    int counter = 0;
    List<String> list = Arrays.asList("marko", "antonio", "rodriguez", "was", "here", ".");
    Pipe<String, String> pipe = new SideEffectFunctionPipe(new CountPipeFunction(count));
    pipe.setStarts(list);
    while (pipe.hasNext()) {
        assertTrue(list.contains(pipe.next()));
        counter++;
    }
    assertEquals(count.get(), list.size());
    assertEquals(count.get(), counter);
}

84. RoundRobinReplicaSelection#selectServer()

Project: pinot
File: RoundRobinReplicaSelection.java
@Override
public ServerInstance selectServer(SegmentId p, List<ServerInstance> orderedServers, Object bucketKey) {
    int size = orderedServers.size();
    if (size <= 0) {
        return null;
    }
    AtomicInteger a = _nextPositionMap.get(p);
    // Create a new position tracker for the partition if it is not available
    if (null == a) {
        synchronized (this) {
            a = _nextPositionMap.get(p);
            if (null == a) {
                a = new AtomicInteger(-1);
                _nextPositionMap.put(p, a);
            }
        }
    }
    return orderedServers.get(Math.abs(a.incrementAndGet()) % size);
}

85. JobMapConcurrencyTest#updateGetAndReplaceConcurrently()

Project: pentaho-kettle
File: JobMapConcurrencyTest.java
@Test
public void updateGetAndReplaceConcurrently() throws Exception {
    AtomicBoolean condition = new AtomicBoolean(true);
    AtomicInteger generator = new AtomicInteger(10);
    List<Updater> updaters = new ArrayList<>();
    for (int i = 0; i < updatersAmount; i++) {
        Updater updater = new Updater(jobMap, generator, updatersCycles);
        updaters.add(updater);
    }
    List<Getter> getters = new ArrayList<>();
    for (int i = 0; i < gettersAmount; i++) {
        getters.add(new Getter(jobMap, condition));
    }
    List<Replacer> replacers = new ArrayList<>();
    for (int i = 0; i < replaceAmount; i++) {
        replacers.add(new Replacer(jobMap, condition));
    }
    //noinspection unchecked
    ConcurrencyTestRunner.runAndCheckNoExceptionRaised(updaters, ListUtils.union(replacers, getters), condition);
}

86. StepMockHelper#getMockInputRowSet()

Project: pentaho-kettle
File: StepMockHelper.java
public RowSet getMockInputRowSet(final List<Object[]> rows) {
    final AtomicInteger index = new AtomicInteger(0);
    RowSet rowSet = mock(RowSet.class, Mockito.RETURNS_MOCKS);
    Answer<Object[]> answer = new Answer<Object[]>() {

        @Override
        public Object[] answer(InvocationOnMock invocation) throws Throwable {
            int i = index.getAndIncrement();
            return i < rows.size() ? rows.get(i) : null;
        }
    };
    when(rowSet.getRowWait(anyLong(), any(TimeUnit.class))).thenAnswer(answer);
    when(rowSet.getRow()).thenAnswer(answer);
    when(rowSet.isDone()).thenAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            return index.get() >= rows.size();
        }
    });
    return rowSet;
}

87. TestTaskReuse#testTaskReusedByTwoPlans()

Project: parseq
File: TestTaskReuse.java
@Test
public void testTaskReusedByTwoPlans() {
    final AtomicInteger counter = new AtomicInteger();
    Task<String> task = Task.callable(() -> {
        counter.incrementAndGet();
        return "hello";
    });
    Task<String> plan1 = task.map( s -> s + " on earth!");
    Task<String> plan2 = task.map( s -> s + " on moon!");
    runAndWait("TestTaskReuse.testTaskReusedByTwoPlans-plan1", plan1);
    runAndWait("TestTaskReuse.testTaskReusedByTwoPlans-plan2", plan2);
    assertEquals(counter.get(), 1);
    assertEquals(countTasks(plan1.getTrace()), 3);
    assertEquals(countTasks(plan2.getTrace()), 3);
}

88. TestTaskReuse#testShareableWithPar()

Project: parseq
File: TestTaskReuse.java
@Test
public void testShareableWithPar() {
    final AtomicInteger counter = new AtomicInteger();
    Task<String> task = Task.callable("increaser", () -> {
        counter.incrementAndGet();
        return "hello";
    });
    Task<String> test = Task.par(task.shareable().map( x -> x + "1"), task.shareable().map( x -> x + "2")).map(( a,  b) -> a + b);
    runAndWait("TestTaskReuse.testShareableWithPar", test);
    assertEquals(counter.get(), 1);
    assertEquals(test.get(), "hello1hello2");
}

89. TestTaskReuse#testLastTaskAlreadyResolvedShareable()

Project: parseq
File: TestTaskReuse.java
@Test
public void testLastTaskAlreadyResolvedShareable() {
    final AtomicInteger counter = new AtomicInteger();
    final Task<String> bob = Task.value("bob", "bob");
    runAndWait("TestTaskReuse.testLastTaskAlreadyResolvedShareable-bob", bob);
    Task<String> task = Task.callable("increaser", () -> {
        counter.incrementAndGet();
        return "hello";
    });
    Task<String> test1 = task.andThen(bob.shareable());
    runAndWait("TestTaskReuse.testLastTaskAlreadyResolvedShareable", test1);
    assertEquals(counter.get(), 1);
}

90. TestTaskReuse#testLastTaskAlreadyResolved()

Project: parseq
File: TestTaskReuse.java
/**
   * In this case the "increaser" task is not being executed because
   * the "bob" task has already been resolved and test1 task is
   * resolved immediately.
   */
@Test
public void testLastTaskAlreadyResolved() {
    final AtomicInteger counter = new AtomicInteger();
    final Task<String> bob = Task.value("bob", "bob");
    runAndWait("TestTaskReuse.testLastTaskResolved-bob", bob);
    Task<String> task = Task.callable("increaser", () -> {
        counter.incrementAndGet();
        return "hello";
    });
    Task<String> test1 = task.andThen(bob);
    runAndWait("TestTaskReuse.testLastTaskResolved", test1);
    assertEquals(counter.get(), 0);
}

91. TestTaskReuse#testExecuteMultipleTimes()

Project: parseq
File: TestTaskReuse.java
@Test
public void testExecuteMultipleTimes() {
    final AtomicInteger counter = new AtomicInteger();
    Task<String> task = Task.callable(() -> {
        counter.incrementAndGet();
        return "hello";
    });
    runAndWait("TestTaskReuse.testExecuteMultipleTimes-1", task);
    runAndWait("TestTaskReuse.testExecuteMultipleTimes-2", task);
    runAndWait("TestTaskReuse.testExecuteMultipleTimes-3", task);
    assertEquals(counter.get(), 1);
}

92. TestParTask#testIterableSeqWithMultipleElements()

Project: parseq
File: TestParTask.java
@Test
public void testIterableSeqWithMultipleElements() throws InterruptedException {
    final int iters = 500;
    final Task<?>[] tasks = new BaseTask<?>[iters];
    final AtomicInteger counter = new AtomicInteger(0);
    for (int i = 0; i < iters; i++) {
        tasks[i] = Task.action("task-" + i, () -> {
            // Note: We intentionally do not use CAS. We guarantee that
            // the run method of Tasks are never executed in parallel.
            final int currentCount = counter.get();
            counter.set(currentCount + 1);
        });
    }
    final ParTask<?> par = par(Arrays.asList(tasks));
    runAndWait("TestParTask.testIterableSeqWithMultipleElements", par);
    assertEquals(500, par.getSuccessful().size());
    assertEquals(500, par.getTasks().size());
    assertEquals(500, par.get().size());
    assertEquals(500, counter.get());
}

93. OutsideEventBusTest#anonymous()

Project: otto
File: OutsideEventBusTest.java
/*
   * If you do this test from common.eventbus.BusTest, it doesn't actually test the behavior.
   * That is, even if exactly the same method works from inside the common.eventbus package tests,
   * it can fail here.
   */
@Test
public void anonymous() {
    final AtomicReference<String> holder = new AtomicReference<String>();
    final AtomicInteger deliveries = new AtomicInteger();
    Bus bus = new Bus(ThreadEnforcer.ANY);
    bus.register(new Object() {

        @Subscribe
        public void accept(String str) {
            holder.set(str);
            deliveries.incrementAndGet();
        }
    });
    String EVENT = "Hello!";
    bus.post(EVENT);
    assertEquals("Only one event should be delivered.", 1, deliveries.get());
    assertEquals("Correct string should be delivered.", EVENT, holder.get());
}

94. ExecutorUtilsTest#testNow()

Project: oryx
File: ExecutorUtilsTest.java
@Test
public void testNow() {
    final AtomicInteger count = new AtomicInteger();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Callable<Object>() {

        @Override
        public Void call() throws InterruptedException {
            Thread.sleep(500L);
            count.incrementAndGet();
            return null;
        }
    });
    ExecutorUtils.shutdownNowAndAwait(executor);
    assertEquals(0, count.get());
}

95. DbListenerTest#testEmbeddedDbListenersCommands()

Project: orientdb
File: DbListenerTest.java
@Test
public void testEmbeddedDbListenersCommands() throws IOException {
    if (database.getURL().startsWith("remote:"))
        return;
    if (database.exists())
        ODatabaseHelper.deleteDatabase(database, getStorageType());
    ODatabaseHelper.createDatabase(database, url, getStorageType());
    final AtomicInteger recordedChanges = new AtomicInteger();
    database.open("admin", "admin");
    database.registerListener(new DbListener());
    String iText = "select from OUser";
    Object execute = database.command(new OSQLSynchQuery<Object>(iText)).execute();
    Assert.assertEquals(execute, commandResult);
    Assert.assertEquals(iText, command);
    ODatabaseHelper.deleteDatabase(database, getStorageType());
    ODatabaseHelper.createDatabase(database, url, getStorageType());
}

96. SplittableRandomTest#testBoundedDoubles()

Project: openjdk
File: SplittableRandomTest.java
/**
     * Each of a parallel sized stream of bounded doubles is within bounds
     */
public void testBoundedDoubles() {
    AtomicInteger fails = new AtomicInteger(0);
    SplittableRandom r = new SplittableRandom();
    long size = 456;
    for (double least = 0.00011; least < 1.0e20; least *= 9) {
        for (double bound = least * 1.0011; bound < 1.0e20; bound *= 17) {
            final double lo = least, hi = bound;
            r.doubles(size, lo, hi).parallel().forEach( x -> {
                if (x < lo || x >= hi)
                    fails.getAndIncrement();
            });
        }
    }
    assertEquals(fails.get(), 0);
}

97. SplittableRandomTest#testBoundedLongs()

Project: openjdk
File: SplittableRandomTest.java
/**
     * Each of a parallel sized stream of bounded longs is within bounds
     */
public void testBoundedLongs() {
    AtomicInteger fails = new AtomicInteger(0);
    SplittableRandom r = new SplittableRandom();
    long size = 123L;
    for (long least = -86028121; least < MAX_LONG_BOUND; least += 1982451653L) {
        for (long bound = least + 2; bound > least && bound < MAX_LONG_BOUND; bound += Math.abs(bound * 7919)) {
            final long lo = least, hi = bound;
            r.longs(size, lo, hi).parallel().forEach( x -> {
                if (x < lo || x >= hi)
                    fails.getAndIncrement();
            });
        }
    }
    assertEquals(fails.get(), 0);
}

98. SplittableRandomTest#testBoundedInts()

Project: openjdk
File: SplittableRandomTest.java
/**
     * Each of a parallel sized stream of bounded ints is within bounds
     */
public void testBoundedInts() {
    AtomicInteger fails = new AtomicInteger(0);
    SplittableRandom r = new SplittableRandom();
    long size = 12345L;
    for (int least = -15485867; least < MAX_INT_BOUND; least += 524959) {
        for (int bound = least + 2; bound > least && bound < MAX_INT_BOUND; bound += 67867967) {
            final int lo = least, hi = bound;
            r.ints(size, lo, hi).parallel().forEach( x -> {
                if (x < lo || x >= hi)
                    fails.getAndIncrement();
            });
        }
    }
    assertEquals(fails.get(), 0);
}

99. PatternStreamTest#testReplaceAll()

Project: openjdk
File: PatternStreamTest.java
@Test(dataProvider = "Patterns")
public void testReplaceAll(String description, String input, Pattern pattern) {
    // Derive expected result from Matcher.replaceAll(String )
    String expected = pattern.matcher(input).replaceAll("R");
    String actual = pattern.matcher(input).replaceAll( r -> "R");
    assertEquals(actual, expected);
    // Derive expected result from Matcher.find
    Matcher m = pattern.matcher(input);
    int expectedMatches = 0;
    while (m.find()) {
        expectedMatches++;
    }
    AtomicInteger actualMatches = new AtomicInteger();
    pattern.matcher(input).replaceAll( r -> "R" + actualMatches.incrementAndGet());
    assertEquals(expectedMatches, actualMatches.get());
}

100. RandomTest#testBoundedDoubles()

Project: openjdk
File: RandomTest.java
/**
     * Each of a sequential sized stream of bounded doubles is within bounds
     */
public void testBoundedDoubles() {
    AtomicInteger fails = new AtomicInteger(0);
    Random r = new Random();
    long size = 456;
    for (double least = 0.00011; least < 1.0e20; least *= 9) {
        for (double bound = least * 1.0011; bound < 1.0e20; bound *= 17) {
            final double lo = least, hi = bound;
            r.doubles(size, lo, hi).forEach( x -> {
                if (x < lo || x >= hi)
                    fails.getAndIncrement();
            });
        }
    }
    assertEquals(fails.get(), 0);
}