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. TestConcurrentUseOfDefaultManagerConnection#setUp()

View license
@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();
}

2. BoltInstanceTest#after()

Project: heron
Source File: BoltInstanceTest.java
View license
@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. VOA#main()

Project: HtmlExtractor
Source File: VOA.java
View license
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));
}

4. TestContinuations#testOnSuccessCalled()

Project: parseq
Source File: TestContinuations.java
View license
@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. ServiceDiscoveryImplTest#setup()

Project: qbit
Source File: ServiceDiscoveryImplTest.java
View license
@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();
}

6. IndexedRingBufferTest#addThousands()

Project: RxJava
Source File: IndexedRingBufferTest.java
View license
@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());
}

7. SimpleTextSimilarity#scoreImpl()

Project: word
Source File: SimpleTextSimilarity.java
View license
/**
     * ???????
     * @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;
}

8. TestAsyncSemaphore#testSingleThreadBoundedConcurrency()

Project: airlift
Source File: TestAsyncSemaphore.java
View license
@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);
}

9. TestAsyncSemaphore#testMultiThreadBoundedConcurrency()

Project: airlift
Source File: TestAsyncSemaphore.java
View license
@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);
}

10. TypesMatchTest#testMethodLocalMaskingTypesMatch()

View license
@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());
}

11. EventCountSnapshotterTrigger#decorateForAppend()

View license
@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;
}

12. JGroupsConnectorTest#testJoinMessageReceivedForDisconnectedHost()

View license
@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);
}

13. JgroupsConnectorTest_Gossip#testConnectorRecoversWhenGossipRouterReconnects()

View license
@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);
}

14. WriteBufferTest#oneProducer_oneConsumer()

Project: caffeine
Source File: WriteBufferTest.java
View license
/* ---------------- 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));
}

15. SingleConsumerQueueTest#oneProducer_oneConsumer()

View license
/* ---------------- 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()));
}

16. SparkTransactionServiceTest#testExplicitTransaction()

View license
/**
   * 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));
}

17. NormalizedNodePrunerTest#countNodes()

View license
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();
}

18. AutoclosingTest#autoClosingLimit1()

Project: cyclops-react
Source File: AutoclosingTest.java
View license
@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()));
}

19. AutoclosingTest#autoClosingZip()

Project: cyclops-react
Source File: AutoclosingTest.java
View license
@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()));
}

20. SetBindingTest#multiValueBindings_WithSingletonAndDefaultValues()

Project: dagger
Source File: SetBindingTest.java
View license
@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);
}

21. SetBindingTest#multiValueBindings_WithSingletonsAcrossMultipleInjectableTypes()

Project: dagger
Source File: SetBindingTest.java
View license
@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);
}

22. InvokedynamicTransformer#findInvokeDynamic()

View license
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();
}

23. InvokedynamicTransformer#cleanup()

View license
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();
}

24. ReflectionObfuscationTransformer#count()

View license
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();
}

25. ReflectionObfuscationTransformer#findReflectionObfuscation()

View license
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();
}

26. TestMarshallingUtilsTest#testCompareAtomicPrimitives()

View license
@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));
}

27. ParallelIterate2Test#creationAndExecution()

View license
/**
     * 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());
}

28. ParallelIterate2Test#creationAndExecution()

View license
/**
     * 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());
}

29. ElementsTest#testModulesAreInstalledAtMostOnce()

Project: guice
Source File: ElementsTest.java
View license
// 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());
}

30. SpoutInstanceTest#before()

Project: heron
Source File: SpoutInstanceTest.java
View license
@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);
}

31. SpoutInstanceTest#after()

Project: heron
Source File: SpoutInstanceTest.java
View license
@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;
}

32. IndexManager#incrementRegionCount()

Project: hindex
Source File: IndexManager.java
View license
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();
}

33. CompactionRequest#getCompactionState()

Project: hindex
Source File: CompactionRequest.java
View license
/**
     * 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;
    }
}

34. GridCacheRebalancingSyncSelfTest#checkPartitionMapMessagesAbsent()

View license
/**
     * @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);
}

35. DummyService#cancel()

Project: ignite
Source File: DummyService.java
View license
/** {@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());
}

36. DummyService#init()

Project: ignite
Source File: DummyService.java
View license
/** {@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());
}

37. DummyService#execute()

Project: ignite
Source File: DummyService.java
View license
/** {@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();
}

38. GridNioSessionMetaKeySelfTest#testNextRandomKey()

View license
/**
     * @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);
}

39. GridTestMessageListener#apply()

Project: ignite
Source File: GridTestMessageListener.java
View license
/** {@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;
}

40. RequestQueueTest#testAdd_dedupeByCacheKey()

Project: iosched
Source File: RequestQueueTest.java
View license
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();
}

41. CommandDefault#next()

Project: isis
Source File: CommandDefault.java
View license
@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();
}

42. SinglePromiseTest#testFailWait()

Project: jdeferred
Source File: SinglePromiseTest.java
View license
@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());
}

43. MPerf#sendMessages()

Project: JGroups
Source File: MPerf.java
View license
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);
    }
}

44. DataPointsMonitor#addCounter()

Project: kairosdb
Source File: DataPointsMonitor.java
View license
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);
}

45. FlatMapOpTest#testClose()

Project: openjdk
Source File: FlatMapOpTest.java
View license
@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());
}

46. OAbstractProfiler#reportTip()

Project: orientdb
Source File: OAbstractProfiler.java
View license
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();
}

47. TestContinuations#testOnSuccessNotCalledWhenException()

Project: parseq
Source File: TestContinuations.java
View license
@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);
}

48. AgentInfoSenderTest#agentInfoShouldBeSent()

Project: pinpoint
Source File: AgentInfoSenderTest.java
View license
@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());
}

49. TestMemoryMessageStore#getMessageCount()

View license
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();
}

50. FluxTests#testStreamBatchesResults()

Project: reactor-core
Source File: FluxTests.java
View license
@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));
}

51. ConnectionPool#initConnections()

Project: redisson
Source File: ConnectionPool.java
View license
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);
    }
}

52. BlockingEventHandlerTest#testSingle()

Project: reef
Source File: BlockingEventHandlerTest.java
View license
@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());
}

53. BlockingEventHandlerTest#testMultiple()

Project: reef
Source File: BlockingEventHandlerTest.java
View license
@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());
}

54. QueryTest#testReactivePull()

Project: RxCupboard
Source File: QueryTest.java
View license
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());
}

55. OperatorZipTest#testBackpressureSync()

Project: RxJava
Source File: OperatorZipTest.java
View license
@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));
}

56. OperatorZipTest#testBackpressureAsync()

Project: RxJava
Source File: OperatorZipTest.java
View license
@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));
}

57. OperatorZipTest#testDownstreamBackpressureRequestsWithFiniteSyncObservables()

Project: RxJava
Source File: OperatorZipTest.java
View license
@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));
}

58. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteAsyncObservables()

Project: RxJava
Source File: OperatorZipTest.java
View license
@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));
}

59. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteSyncObservables()

Project: RxJava
Source File: OperatorZipTest.java
View license
@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));
}

60. IndexedRingBufferTest#removeEnd()

Project: RxJava
Source File: IndexedRingBufferTest.java
View license
@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());
}

61. OnSubscribeCacheResetableTest#test()

View license
@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());
}

62. OnSubscribeDoOnEmptyTest#subscriberStateTest()

View license
@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);
}

63. QueryTest#testAtomicIntegers()

Project: squidb
Source File: QueryTest.java
View license
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();
    }
}

64. IntStreamExTest#testPeekFirst()

Project: streamex
Source File: IntStreamExTest.java
View license
@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());
}

65. ProxyIp#toVerify()

Project: superword
Source File: ProxyIp.java
View license
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;
}

66. UIHelpers#openOnUIThread()

View license
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();
}

67. LazyFutureTest#testLazyness()

View license
@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());
}

68. TitanGraphTest#executeSerialTransaction()

Project: titan
Source File: TitanGraphTest.java
View license
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();
}

69. CountLatchTest#supportsIncrementingAndDecrementing()

Project: totallylazy
Source File: CountLatchTest.java
View license
@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));
}

70. ClassNamer#get()

Project: transfuse
Source File: ClassNamer.java
View license
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();
}

71. UniqueVariableNamer#nullSafeIterGet()

Project: transfuse
Source File: UniqueVariableNamer.java
View license
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();
}

72. InlineEnclosureTest#childrenByType()

Project: wicket
Source File: InlineEnclosureTest.java
View license
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();
}

73. EHCacheManagerHolder#getCacheManager()

Project: wss4j
Source File: EHCacheManagerHolder.java
View license
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;
}

74. AngularObjectTest#testWatcher()

Project: zeppelin
Source File: AngularObjectTest.java
View license
@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());
}

75. FileWrapperJournal#appendCommitRecord()

View license
@Override
public void appendCommitRecord(long txID, boolean sync, IOCompletion callback, boolean lineUpContext) throws Exception {
    JournalInternalRecord commitRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, txID, null);
    AtomicInteger value = transactions.remove(Long.valueOf(txID));
    if (value != null) {
        commitRecord.setNumberOfRecords(value.get());
    }
    writeRecord(commitRecord, true, callback);
}

76. FileWrapperJournal#appendPrepareRecord()

View license
@Override
public void appendPrepareRecord(long txID, EncodingSupport transactionData, boolean sync, IOCompletion callback) throws Exception {
    JournalInternalRecord prepareRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, txID, transactionData);
    AtomicInteger value = transactions.get(Long.valueOf(txID));
    if (value != null) {
        prepareRecord.setNumberOfRecords(value.get());
    }
    writeRecord(prepareRecord, sync, callback);
}

77. NetworkReconnectTest#xtestWithoutRestarts()

View license
public void xtestWithoutRestarts() throws Exception {
    startProducerBroker();
    startConsumerBroker();
    MessageConsumer consumer = createConsumer();
    AtomicInteger counter = createConsumerCounter(producerConnectionFactory);
    waitForConsumerToArrive(counter);
    String messageId = sendMessage();
    Message message = consumer.receive(1000);
    assertEquals(messageId, message.getJMSMessageID());
    assertNull(consumer.receiveNoWait());
}

78. NetworkReconnectTest#xtestWithConsumerBrokerStartDelay()

View license
public void xtestWithConsumerBrokerStartDelay() throws Exception {
    startConsumerBroker();
    MessageConsumer consumer = createConsumer();
    Thread.sleep(1000 * 5);
    startProducerBroker();
    AtomicInteger counter = createConsumerCounter(producerConnectionFactory);
    waitForConsumerToArrive(counter);
    String messageId = sendMessage();
    Message message = consumer.receive(1000);
    assertEquals(messageId, message.getJMSMessageID());
    assertNull(consumer.receiveNoWait());
}

79. NetworkReconnectTest#xtestWithProducerBrokerStartDelay()

View license
public void xtestWithProducerBrokerStartDelay() throws Exception {
    startProducerBroker();
    AtomicInteger counter = createConsumerCounter(producerConnectionFactory);
    Thread.sleep(1000 * 5);
    startConsumerBroker();
    MessageConsumer consumer = createConsumer();
    waitForConsumerToArrive(counter);
    String messageId = sendMessage();
    Message message = consumer.receive(1000);
    assertEquals(messageId, message.getJMSMessageID());
    assertNull(consumer.receiveNoWait());
}

80. NetworkReconnectTest#createConsumerCounter()

View license
protected AtomicInteger createConsumerCounter(ActiveMQConnectionFactory cf) throws Exception {
    final AtomicInteger rc = new AtomicInteger(0);
    Connection connection = cf.createConnection();
    connections.add(connection);
    connection.start();
    ConsumerEventSource source = new ConsumerEventSource(connection, destination);
    source.setConsumerListener(new ConsumerListener() {

        @Override
        public void onConsumerEvent(ConsumerEvent event) {
            rc.set(event.getConsumerCount());
        }
    });
    source.start();
    return rc;
}

81. MDBMultipleHandlersServerDisconnectTest#doReceiveMessage()

View license
private void doReceiveMessage(ClientMessage message) throws Exception {
    Assert.assertNotNull(message);
    message.acknowledge();
    Integer value = message.getIntProperty("i");
    AtomicInteger mapCount = new AtomicInteger(1);
    mapCount = mapCounter.putIfAbsent(value, mapCount);
    if (mapCount != null) {
        mapCount.incrementAndGet();
    }
}

82. TestAbstractServiceHolder#test_disposing_gracefully_when_terminated()

View license
@Test(timeout = 2000)
public void test_disposing_gracefully_when_terminated() {
    final int numberOfInstances = 100;
    final AtomicInteger numberOfInstancesTerminatedGracefully = new AtomicInteger();
    ServiceDestroyer<Object> serviceDestroyer = new ServiceDestroyer<Object>() {

        public void destroy(Object instance) {
            numberOfInstancesTerminatedGracefully.incrementAndGet();
        }

        ;
    };
    for (int i = 0; i < numberOfInstances; i++) {
        // delay  is lesser than termination timeout
        scheduler.scheduleForDisposal(new DisposableReference<>(instance, serviceDestroyer), 100);
    }
    scheduler.terminate();
    assertEquals("all instances should be terminated gracefully", numberOfInstances, numberOfInstancesTerminatedGracefully.get());
}

83. TestAsyncSemaphore#testInlineExecution()

Project: airlift
Source File: TestAsyncSemaphore.java
View license
@Test
public void testInlineExecution() throws Exception {
    AsyncSemaphore<Runnable> asyncSemaphore = new AsyncSemaphore<>(1, executor,  task -> newDirectExecutorService().submit(task));
    AtomicInteger count = new AtomicInteger();
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        futures.add(asyncSemaphore.submit(count::incrementAndGet));
    }
    // Wait for completion
    Futures.allAsList(futures).get(1, TimeUnit.MINUTES);
    Assert.assertEquals(count.get(), 1000);
}

84. EventApiController#validateAdditionalTicketFields()

Project: alf.io
Source File: EventApiController.java
View license
private ValidationResult validateAdditionalTicketFields(List<EventModification.AdditionalField> ticketFields, Errors errors) {
    //meh
    AtomicInteger cnt = new AtomicInteger();
    return Optional.ofNullable(ticketFields).orElseGet(Collections::emptyList).stream().map( field -> {
        String prefix = "ticketFields[" + cnt.getAndIncrement() + "]";
        if (StringUtils.isBlank(field.getName())) {
            errors.rejectValue(prefix + ".name", "error.required");
        }
        return Validator.evaluateValidationResult(errors);
    }).reduce(ValidationResult::or).orElseGet(ValidationResult::success);
}

85. MultiIntentService#onCreate()

View license
@Override
public void onCreate() {
    super.onCreate();
    LogUtils.v(BASE_TAG, "onCreate()");
    mRetainCount = new AtomicInteger(0);
    mFutures = new ConcurrentHashMap<String, Future<?>>();
    mAutoCloseEnable = true;
    mAutoCloseTime = AUTO_CLOSE_DEFAULT_TIME;
    ensureHandler();
    ensureExecutor();
    checkAutoClose();
}

86. PriorityObjectBlockingQueue#put()

View license
public void put(E e) throws InterruptedException {
    if (e == null)
        throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        while (count.get() == capacity) {
            notFull.await();
        }
        opQueue(node);
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
}

87. PriorityObjectBlockingQueue#offer()

View license
public boolean offer(E e) {
    if (e == null)
        throw new NullPointerException();
    final AtomicInteger count = this.count;
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        if (count.get() < capacity) {
            opQueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}

88. PriorityObjectBlockingQueue#take()

View license
public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        while (count.get() == 0) {
            notEmpty.await();
        }
        x = opQueue(null);
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

89. PriorityObjectBlockingQueue#poll()

View license
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    E x = null;
    int c = -1;
    long nanos = unit.toNanos(timeout);
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
        while (count.get() == 0) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        x = opQueue(null);
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

90. PriorityObjectBlockingQueue#poll()

View license
public E poll() {
    final AtomicInteger count = this.count;
    if (count.get() == 0)
        return null;
    E x = null;
    int c = -1;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        if (count.get() > 0) {
            x = opQueue(null);
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        }
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

91. MigrationEngineTest#justRun()

View license
@Test
public void justRun() throws Exception {
    final AtomicInteger value = new AtomicInteger();
    OrmaDatabase orma = OrmaFactory.builder().versionForManualStepMigration(100).migrationStep(10, new ManualStepMigration.ChangeStep() {

        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            value.addAndGet(10);
        }
    }).migrationStep(11, new ManualStepMigration.ChangeStep() {

        @Override
        public void change(@NonNull ManualStepMigration.Helper helper) {
            value.addAndGet(11);
        }
    }).build();
    orma.migrate();
    assertThat("No migration on initialization", value.get(), is(0));
}

92. TypesMatchTest#testBasicTypesMatch()

View license
@Test
public void testBasicTypesMatch() {
    final AtomicInteger hit = new AtomicInteger();
    Source s = new Source(SIMPLE_SOURCE, "SimpleTypesMatchTest.java");
    s.parseCompilationUnit();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            assertTrue("typesMatch with star import should match but fails:" + node.astReturnTypeReference(), new Resolver().typesMatch("java.util.List", node.astReturnTypeReference()));
            assertFalse("typesMatch with no relevant imports should fail but matches", new Resolver().typesMatch("java.awt.List", node.astReturnTypeReference()));
            hit.incrementAndGet();
            return true;
        }
    });
    assertEquals("expected 1 hit on MethodDeclaration", 1, hit.get());
}

93. TypesMatchTest#testInnerMaskingTypesMatch()

View license
@Test
public void testInnerMaskingTypesMatch() {
    Source s = new Source(INNER_MASKING_SOURCE, "MaskingTypesMatchTest.java");
    s.parseCompilationUnit();
    final AtomicInteger hit = new AtomicInteger();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            assertFalse("typesMatch with star import but should fail due to inner masking, yet succeeds.", new Resolver().typesMatch("java.util.List", node.astReturnTypeReference()));
            hit.incrementAndGet();
            return true;
        }
    });
    assertEquals("expected 1 hit on MethodDeclaration", 1, hit.get());
}

94. TypesMatchTest#testTopLevelMaskingTypesMatch()

View license
@Test
public void testTopLevelMaskingTypesMatch() {
    Source s = new Source(TOP_LEVEL_MASKING_SOURCE, "MaskingTypesMatchTest.java");
    s.parseCompilationUnit();
    final AtomicInteger hit = new AtomicInteger();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            assertFalse("typesMatch with star import but should fail due to top level masking, yet succeeds.", new Resolver().typesMatch("java.util.List", node.astReturnTypeReference()));
            hit.incrementAndGet();
            return true;
        }
    });
    assertEquals("expected 1 hit on MethodDeclaration", 1, hit.get());
}

95. TypesMatchTest#testArrayTypesMatch()

View license
@Test
public void testArrayTypesMatch() {
    Source s = new Source(ARRAYS_SOURCE, "ArrayTypesMatchTest.java");
    s.parseCompilationUnit();
    final AtomicInteger hit = new AtomicInteger();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            assertTrue("typesMatch with String[] should match java.lang.String[] but doesn't.", new Resolver().typesMatch("java.lang.String[]", node.astReturnTypeReference()));
            assertFalse("typesMatch with String[] should NOT match java.lang.String[][] but does.", new Resolver().typesMatch("java.lang.String[][]", node.astReturnTypeReference()));
            assertFalse("typesMatch with String[] should NOT match java.lang.String but does.", new Resolver().typesMatch("java.lang.String", node.astReturnTypeReference()));
            assertTrue("typesMatch with String should match java.lang.String but doesn't.", new Resolver().typesMatch("java.lang.String", node.astParameters().first().astTypeReference()));
            assertFalse("typesMatch with String should NOT match java.lang.String[] but does.", new Resolver().typesMatch("java.lang.String[]", node.astParameters().first().astTypeReference()));
            hit.incrementAndGet();
            return true;
        }
    });
    assertEquals("expected 1 hit on MethodDeclaration", 1, hit.get());
}

96. TypesMatchTest#testImportedTypesMatch()

View license
@Test
public void testImportedTypesMatch() {
    Source s = new Source(IMPORTS_SOURCE, "ImportsTest.java");
    s.parseCompilationUnit();
    final AtomicInteger hit = new AtomicInteger();
    s.getNodes().get(0).accept(new ForwardingAstVisitor() {

        @Override
        public boolean visitMethodDeclaration(MethodDeclaration node) {
            assertFalse("typesMatch with java.awt.List+java.util.* imported should NOT match java.util.List", new Resolver().typesMatch("java.util.List", node.astReturnTypeReference()));
            assertTrue("typesMatch with java.awt.List+java.util.* imported SHOULD match java.awt.List", new Resolver().typesMatch("java.awt.List", node.astReturnTypeReference()));
            hit.incrementAndGet();
            return true;
        }
    });
    assertEquals("expected 1 hit on MethodDeclaration", 1, hit.get());
}

97. NoTransactionContextTest#testPreCompletion()

View license
@Test
public void testPreCompletion() throws Exception {
    AtomicInteger value = new AtomicInteger(0);
    ctx.preCompletion(() -> value.compareAndSet(1, 5));
    assertEquals(0, value.getAndSet(1));
    ctx.finish();
    assertEquals(5, value.get());
}

98. NoTransactionContextTest#testPreCompletionFail()

View license
@Test
public void testPreCompletionFail() throws Exception {
    AtomicInteger value = new AtomicInteger(0);
    ctx.preCompletion(() -> value.compareAndSet(1, 5));
    assertEquals(0, value.getAndSet(1));
    ctx.recordFailure(new Exception());
    ctx.finish();
    assertEquals(5, value.get());
}

99. NoTransactionContextTest#testPostCompletion()

View license
@Test
public void testPostCompletion() throws Exception {
    AtomicInteger value = new AtomicInteger(0);
    ctx.postCompletion( status -> {
        assertEquals(NO_TRANSACTION, status);
        value.compareAndSet(1, 5);
    });
    assertEquals(0, value.getAndSet(1));
    ctx.finish();
    assertEquals(5, value.get());
}

100. NoTransactionContextTest#testPostCompletionFail()

View license
@Test
public void testPostCompletionFail() throws Exception {
    AtomicInteger value = new AtomicInteger(0);
    ctx.postCompletion( status -> {
        assertEquals(NO_TRANSACTION, status);
        value.compareAndSet(1, 5);
    });
    assertEquals(0, value.getAndSet(1));
    ctx.recordFailure(new Exception());
    ctx.finish();
    assertEquals(5, value.get());
}