Here are the examples of the java api class java.util.concurrent.atomic.AtomicInteger taken from open source projects.
1. SimpleTextSimilarity#scoreImpl()
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; }
2. IndexedRingBufferTest#addThousands()
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()); }
3. TestContinuations#testOnSuccessCalled()
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); }
4. ServiceDiscoveryImplTest#setup()
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(); }
5. BoltInstanceTest#after()
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; }
6. VOA#main()
View licensepublic 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)); }
7. 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(); }
8. OperatorZipTest#testBackpressureSync()
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)); }
9. UniqueVariableNamer#nullSafeIterGet()
View licenseprivate 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(); }
10. ClassNamer#get()
View licenseprivate 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(); }
11. CountLatchTest#supportsIncrementingAndDecrementing()
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)); }
12. TitanGraphTest#executeSerialTransaction()
View licenseprivate 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(); }
13. 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); }
14. 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()); }
15. IndexedRingBufferTest#removeEnd()
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()); }
16. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteSyncObservables()
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)); }
17. OperatorZipTest#testDownstreamBackpressureRequestsWithInfiniteAsyncObservables()
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)); }
18. OperatorZipTest#testDownstreamBackpressureRequestsWithFiniteSyncObservables()
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)); }
19. OperatorZipTest#testBackpressureAsync()
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)); }
20. QueryTest#testReactivePull()
View licensepublic 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()
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()); }
22. UIHelpers#openOnUIThread()
View licensepublic 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()
View licenseprivate 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()
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()); }
25. QueryTest#testAtomicIntegers()
View licensepublic 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()
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()); }
27. EHCacheManagerHolder#getCacheManager()
View licensepublic 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()
View licenseprivate <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()
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()); }
30. BlockingEventHandlerTest#testSingle()
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()); }
31. ConnectionPool#initConnections()
View licenseprivate 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()
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)); }
33. TestMemoryMessageStore#getMessageCount()
View licensepublic 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()
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(); }
35. RequestQueueTest#testAdd_dedupeByCacheKey()
View licensepublic 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()
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; }
37. AgentInfoSenderTest#agentInfoShouldBeSent()
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()); }
38. TestContinuations#testOnSuccessNotCalledWhenException()
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); }
39. OAbstractProfiler#reportTip()
View licensepublic 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()
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()); }
41. DummyService#execute()
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(); }
42. DummyService#init()
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()); }
43. DummyService#cancel()
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()); }
44. 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); }
45. DataPointsMonitor#addCounter()
View licenseprivate 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); }
46. MPerf#sendMessages()
View licenseprotected 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); } }
47. SinglePromiseTest#testFailWait()
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()); }
48. CompactionRequest#getCompactionState()
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; } }
49. IndexManager#incrementRegionCount()
View licensepublic 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(); }
50. SpoutInstanceTest#after()
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; }
51. SpoutInstanceTest#before()
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); }
52. ElementsTest#testModulesAreInstalledAtMostOnce()
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()); }
53. 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()); }
54. 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)); }
55. ReflectionObfuscationTransformer#findReflectionObfuscation()
View licensepublic 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(); }
56. 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()); }
57. TestAsyncSemaphore#testMultiThreadBoundedConcurrency()
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); }
58. TestAsyncSemaphore#testSingleThreadBoundedConcurrency()
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); }
59. 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()); }
60. 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)); }
61. 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())); }
62. 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); }
63. WriteBufferTest#oneProducer_oneConsumer()
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)); }
64. ReflectionObfuscationTransformer#count()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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()
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); }
68. SetBindingTest#multiValueBindings_WithSingletonAndDefaultValues()
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); }
69. AutoclosingTest#autoClosingZip()
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())); }
70. AutoclosingTest#autoClosingLimit1()
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())); }
71. NormalizedNodePrunerTest#countNodes()
View licenseprivate 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()
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); }
73. 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); }
74. 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; }
75. PriorityObjectBlockingQueue#put()
View licensepublic 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(); }
76. 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(); }
77. EventApiController#validateAdditionalTicketFields()
View licenseprivate 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); }
78. TestAsyncSemaphore#testInlineExecution()
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); }
79. 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()); }
80. MDBMultipleHandlersServerDisconnectTest#doReceiveMessage()
View licenseprivate 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(); } }
81. NetworkReconnectTest#createConsumerCounter()
View licenseprotected 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; }
82. NetworkReconnectTest#xtestWithProducerBrokerStartDelay()
View licensepublic 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()); }
83. NetworkReconnectTest#xtestWithConsumerBrokerStartDelay()
View licensepublic 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()); }
84. NetworkReconnectTest#xtestWithoutRestarts()
View licensepublic 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()); }
85. NopRemover#transform()
View license@Override public void transform() throws Throwable { AtomicInteger counter = new AtomicInteger(); classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> { classNode.methods.stream().filter( methodNode -> methodNode.instructions.getFirst() != null).forEach( methodNode -> { Iterator<AbstractInsnNode> it = methodNode.instructions.iterator(); while (it.hasNext()) { AbstractInsnNode node = it.next(); if (node.getOpcode() == Opcodes.NOP) { it.remove(); counter.getAndIncrement(); } } }); }); System.out.println("Removed " + counter.get() + " nops"); }
86. DeadCodeRemover#transform()
View license@Override public void transform() throws Throwable { AtomicInteger deadInstructions = new AtomicInteger(); classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> { classNode.methods.stream().filter( methodNode -> methodNode.instructions.getFirst() != null).forEach( methodNode -> { try { Map<AbstractInsnNode, List<Frame>> f = MethodAnalyzer.analyze(classes.get(classNode.name), methodNode).getFrames(); Iterator<AbstractInsnNode> iterator = methodNode.instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode next = iterator.next(); if (!(next instanceof LabelNode) && f.get(next) == null) { iterator.remove(); deadInstructions.incrementAndGet(); } } } catch (Throwable ignored) { System.out.println("Error while removing dead code from " + classNode.name + " " + methodNode.name + methodNode.desc); throw ignored; } }); }); System.out.println("Removed " + deadInstructions.get() + " dead instructions"); }
87. ContinousGotoRemover#transform()
View license@Override public void transform() throws Throwable { AtomicInteger counter = new AtomicInteger(); classNodes().stream().map( wrappedClassNode -> wrappedClassNode.classNode).forEach( classNode -> { classNode.methods.stream().filter( methodNode -> methodNode.instructions.getFirst() != null).forEach( methodNode -> { for (int i = 0; i < methodNode.instructions.size(); i++) { AbstractInsnNode node = methodNode.instructions.get(i); if (node.getOpcode() == Opcodes.GOTO) { AbstractInsnNode a = Utils.getNext(node); AbstractInsnNode b = Utils.getNext(((JumpInsnNode) node).label); if (a == b) { methodNode.instructions.remove(node); counter.incrementAndGet(); } } } }); }); System.out.println("Removed " + counter.get() + " continous gotos"); }
88. BaseRegularExpressionValidatorTest#mixedMessagesTest()
View license@Ignore @Test public void mixedMessagesTest() { AtomicInteger count = new AtomicInteger(0); for (StratioStreamingMessage message : getMixedMessages()) { try { this.test(message); } catch (RequestValidationException e) { count.incrementAndGet(); } } Assert.assertTrue(getBadStrings().length <= count.get()); }
89. TestResourceControlledScheduledExecutor#testExecution()
View license@Test public void testExecution() throws Exception { ResourceControlledScheduledExecutor executor = new ResourceControlledScheduledExecutor(0.5f, 1); final AtomicInteger executions = new AtomicInteger(0); Runnable runnable = new Runnable() { @Override public void run() { executions.incrementAndGet(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= 100) ; } }; // the first couple executions will happen quickly but overtime // we should see about 50% of the remaining 9 seconds consumed // with the runnable executing executor.submit(runnable); executor.submit(runnable); TimeUnit.SECONDS.sleep(9); executor.shutdown(); int result = executions.get(); Assert.assertTrue("Expected between 30 and 60 executions but got: " + result, result >= 30 && result <= 60); }
90. InjectionTest#getInstance()
View license@Test public void getInstance() { final AtomicInteger next = new AtomicInteger(0); @Module(injects = Integer.class) class TestModule { @Provides Integer provideInteger() { return next.getAndIncrement(); } } ObjectGraph graph = ObjectGraph.createWith(new TestingLoader(), new TestModule()); assertThat((int) graph.get(Integer.class)).isEqualTo(0); assertThat((int) graph.get(Integer.class)).isEqualTo(1); }
91. InjectionOfLazyTest#sideBySideLazyVsProvider()
View license@Test public void sideBySideLazyVsProvider() { final AtomicInteger counter = new AtomicInteger(); class TestEntryPoint { @Inject Provider<Integer> providerOfInteger; @Inject Lazy<Integer> lazyInteger; } @Module(injects = TestEntryPoint.class) class TestModule { @Provides Integer provideInteger() { return counter.incrementAndGet(); } } TestEntryPoint ep = injectWithModule(new TestEntryPoint(), new TestModule()); assertEquals(0, counter.get()); assertEquals(0, counter.get()); assertEquals(1, ep.lazyInteger.get().intValue()); assertEquals(1, counter.get()); // fresh instance assertEquals(2, ep.providerOfInteger.get().intValue()); // still the same instance assertEquals(1, ep.lazyInteger.get().intValue()); assertEquals(2, counter.get()); // fresh instance assertEquals(3, ep.providerOfInteger.get().intValue()); // still the same instance. assertEquals(1, ep.lazyInteger.get().intValue()); }
92. InjectionOfLazyTest#providerOfLazyOfSomething()
View license@Test public void providerOfLazyOfSomething() { final AtomicInteger counter = new AtomicInteger(); class TestEntryPoint { @Inject Provider<Lazy<Integer>> providerOfLazyInteger; } @Module(injects = TestEntryPoint.class) class TestModule { @Provides Integer provideInteger() { return counter.incrementAndGet(); } } TestEntryPoint ep = injectWithModule(new TestEntryPoint(), new TestModule()); assertEquals(0, counter.get()); Lazy<Integer> i = ep.providerOfLazyInteger.get(); assertEquals(1, i.get().intValue()); assertEquals(1, counter.get()); assertEquals(1, i.get().intValue()); Lazy<Integer> j = ep.providerOfLazyInteger.get(); assertEquals(2, j.get().intValue()); assertEquals(2, counter.get()); assertEquals(1, i.get().intValue()); }
93. InjectionOfLazyTest#lazyNullCreation()
View license@Test public void lazyNullCreation() { final AtomicInteger provideCounter = new AtomicInteger(0); class TestEntryPoint { @Inject Lazy<String> i; } @Module(injects = TestEntryPoint.class) class TestModule { @Provides String provideInteger() { provideCounter.incrementAndGet(); return null; } } TestEntryPoint ep = injectWithModule(new TestEntryPoint(), new TestModule()); assertEquals(0, provideCounter.get()); assertNull(ep.i.get()); assertEquals(1, provideCounter.get()); // still null assertNull(ep.i.get()); // still only called once. assertEquals(1, provideCounter.get()); }
94. InjectionOfLazyTest#lazyValueCreation()
View license@Test public void lazyValueCreation() { final AtomicInteger counter = new AtomicInteger(); class TestEntryPoint { @Inject Lazy<Integer> i; @Inject Lazy<Integer> j; } @Module(injects = TestEntryPoint.class) class TestModule { @Provides Integer provideInteger() { return counter.incrementAndGet(); } } TestEntryPoint ep = injectWithModule(new TestEntryPoint(), new TestModule()); assertEquals(0, counter.get()); assertEquals(1, ep.i.get().intValue()); assertEquals(1, counter.get()); assertEquals(2, ep.j.get().intValue()); assertEquals(1, ep.i.get().intValue()); assertEquals(2, counter.get()); }
95. ModuleAdapterProcessor#bindingClassName()
View licenseprivate ClassName bindingClassName(ClassName adapterName, ExecutableElement providerMethod, Map<ExecutableElement, ClassName> methodToClassName, Map<String, AtomicInteger> methodNameToNextId) { ClassName className = methodToClassName.get(providerMethod); if (className != null) return className; String methodName = providerMethod.getSimpleName().toString(); String suffix = ""; AtomicInteger id = methodNameToNextId.get(methodName); if (id == null) { methodNameToNextId.put(methodName, new AtomicInteger(2)); } else { suffix = id.toString(); id.incrementAndGet(); } String uppercaseMethodName = Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1); className = adapterName.nestedClass(uppercaseMethodName + "ProvidesAdapter" + suffix); methodToClassName.put(providerMethod, className); return className; }
96. RetryNoMocksTest#testRetryEnds()
View license@Test public void testRetryEnds() { count = new AtomicInteger(0); errors = Collections.synchronizedCollection(new ArrayList<>()); final RetryExecutor executor = new AsyncRetryExecutor(Executors.newSingleThreadScheduledExecutor()).retryOn(Throwable.class).withExponentialBackoff(//500ms times 2 after each retry 5, //500ms times 2 after each retry 2).withMaxDelay(//10 miliseconds 0_10).withUniformJitter().withMaxRetries(//add between +/- 100 ms randomly 20); List result = SimpleReact.builder().retrier(executor).build().ofAsync(() -> 1, () -> 2, () -> 3).capture( e -> errors.add(e)).retry(( it) -> { throw new RuntimeException("failed"); }).block(); assertThat(result.size(), is(0)); assertThat(errors.size(), is(3)); }
97. RetryNoMocksTest#testAbort()
View license@Test public void testAbort() { count = new AtomicInteger(0); errors = Collections.synchronizedCollection(new ArrayList<>()); final RetryExecutor executor = new AsyncRetryExecutor(Executors.newSingleThreadScheduledExecutor()); List<Integer> result = new SimpleReact().ofAsync(() -> 1, () -> 2, () -> 3).withRetrier(executor).capture( e -> errors.add(e)).retry( it -> abortOrReturn(it)).block(); assertThat(result.size(), is(2)); assertThat(errors.iterator().next(), instanceOf(AbortRetryException.class)); }
98. RetryNoMocksTest#testRetry()
View license@Test public void testRetry() { count = new AtomicInteger(0); errors = Collections.synchronizedCollection(new ArrayList<>()); final RetryExecutor executor = new AsyncRetryExecutor(Executors.newSingleThreadScheduledExecutor()); List<Integer> result = new SimpleReact().ofAsync(() -> 1, () -> 2, () -> 3).withRetrier(executor).capture( e -> errors.add(e)).retry( it -> throwOrReturn(it)).block(); assertThat(result.size(), is(3)); assertThat(errors.size(), is(0)); }
99. CaptureTest#captureErrorOnce()
View license@Test public void captureErrorOnce() throws InterruptedException { count = new AtomicInteger(0); new SimpleReact().of("hello", "world").capture( e -> count.incrementAndGet()).peek(System.out::println).then(this::exception).peek(System.out::println).then( s -> "hello" + s).run(); Thread.sleep(500); assertEquals(count.get(), 2); }
100. ClientSequencerTest#testSequenceEventAtCommand()
View license/** * Tests sequencing an event that arrives before a command response. */ public void testSequenceEventAtCommand() throws Throwable { ClientSequencer sequencer = new ClientSequencer(new ClientSessionState(UUID.randomUUID())); long sequence = sequencer.nextRequest(); PublishRequest request = PublishRequest.builder().withSession(1).withEventIndex(2).withPreviousIndex(0).build(); CommandResponse response = CommandResponse.builder().withStatus(Response.Status.OK).withIndex(2).withEventIndex(2).build(); AtomicInteger run = new AtomicInteger(); sequencer.sequenceResponse(sequence, response, () -> assertEquals(run.getAndIncrement(), 1)); sequencer.sequenceEvent(request, () -> assertEquals(run.getAndIncrement(), 0)); assertEquals(run.get(), 2); }