Java Code Examples for java.util.concurrent.atomic.LongAdder

The following examples show how to use java.util.concurrent.atomic.LongAdder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: reactor-core   Source File: MonoPeekAfterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void onSuccessNormalConditional() {
	LongAdder invoked = new LongAdder();
	AtomicBoolean hasNull = new AtomicBoolean();

	Mono<Integer> mono = Flux
			.range(1, 10)
			.reduce((a, b) -> a + b)
			.hide()
			.filter(v -> true)
			.doOnSuccess(v -> {
				if (v == null) hasNull.set(true);
				invoked.increment();
			});

	StepVerifier.create(mono)
	            .expectFusion(Fuseable.ANY, Fuseable.NONE)
	            .expectNext(55)
	            .expectComplete()
	            .verify();

	assertFalse("unexpected call to onSuccess with null", hasNull.get());
	assertEquals(1, invoked.intValue());

}
 
Example 2
public HBaseRollForward(TxnSupplier supplier, SConfiguration config) {

        this.firstQueue = new ArrayBlockingQueue<>(config.getRollforwardQueueSize());
        this.secondQueue = new ArrayBlockingQueue<>(config.getRollforwardQueueSize());
        this.firstThreads = config.getRollforwardFirstThreads();
        this.secondThreads = config.getRollforwardSecondThreads();

        this.serviceFirst = Executors.newFixedThreadPool(firstThreads,
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("WritesRollforward-%d").build());
        this.serviceSecond = Executors.newFixedThreadPool(secondThreads,
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("WritesRollforward-retry-%d").build());
        this.supplier = supplier;
        this.firstResolutions = new LongAdder();
        this.secondResolutions = new LongAdder();
        this.firstActive = new LongAdder();
        this.secondActive = new LongAdder();
        this.firstProcessor = new RollForwarder(firstQueue, secondQueue, config.getRollforwardFirstWait(), firstResolutions, firstActive);
        this.secondProcessor = new RollForwarder(secondQueue, null, config.getRollforwardSecondWait(), secondResolutions, secondActive);
    }
 
Example 3
Source Project: reactor-core   Source File: MonoPeekAfterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void onSuccessFusion() {
	LongAdder invoked = new LongAdder();
	AtomicBoolean hasNull = new AtomicBoolean();

	Mono<Integer> mono = Flux
			.range(1, 10)
			.reduce((a, b) -> a + b)
			.doOnSuccess(v -> {
				if (v == null) hasNull.set(true);
				invoked.increment();
			});

	StepVerifier.create(mono)
	            .expectFusion(Fuseable.ASYNC)
	            .expectNext(55)
	            .expectComplete()
	            .verify();

	assertFalse("unexpected call to onSuccess with null", hasNull.get());
	assertEquals(1, invoked.intValue());
}
 
Example 4
Source Project: tlaplus   Source File: SimulationWorkerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testActionPropertyBadEval() throws Exception {
	ITool tool = new FastTool("", "BasicMultiTrace", "MCActionPropBadEval", new SimpleFilenameToStream());
	
	StateVec initStates = tool.getInitStates();
	ILiveCheck liveCheck =  new NoOpLiveCheck(tool, "BasicMultiTrace");
	BlockingQueue<SimulationWorkerResult> resultQueue = new LinkedBlockingQueue<>();
	SimulationWorker worker = new SimulationWorker(0, tool, initStates, resultQueue, 0, 100, 100, false, null,
			liveCheck, new LongAdder(), new LongAdder());
	worker.start();
	
	SimulationWorkerResult res = resultQueue.take();
	
	assertTrue(res.isError());
	SimulationWorkerError err = res.error();
	assertEquals(EC.TLC_ACTION_PROPERTY_EVALUATION_FAILED, err.errorCode);
			
	worker.join();
	assertFalse(worker.isAlive());
}
 
Example 5
Source Project: reactor-core   Source File: FluxBufferPredicateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void requestUnboundedFromStartRequestsSourceOnce() {
	LongAdder requestCallCount = new LongAdder();
	LongAdder totalRequest = new LongAdder();
	Flux<Integer> source = Flux.range(1, 10).hide()
	                           .doOnRequest(r -> requestCallCount.increment())
	                           .doOnRequest(totalRequest::add);

	StepVerifier.withVirtualTime(//start with an unbounded request
			() -> new FluxBufferPredicate<>(source, i -> i % 3 == 0,
					Flux.listSupplier(), FluxBufferPredicate.Mode.UNTIL))
	            .expectSubscription()
	            .expectNext(Arrays.asList(1, 2, 3))
	            .expectNext(Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9))
	            .expectNext(Collections.singletonList(10))
	            .expectComplete()
	            .verify();

	assertThat(requestCallCount.intValue()).isEqualTo(1);
	assertThat(totalRequest.longValue()).isEqualTo(Long.MAX_VALUE); //also unbounded
}
 
Example 6
Source Project: resilience4j   Source File: CircuitBreakerMetrics.java    License: Apache License 2.0 6 votes vote down vote up
private CircuitBreakerMetrics(int slidingWindowSize,
    CircuitBreakerConfig.SlidingWindowType slidingWindowType,
    CircuitBreakerConfig circuitBreakerConfig,
    Clock clock) {
    if (slidingWindowType == CircuitBreakerConfig.SlidingWindowType.COUNT_BASED) {
        this.metrics = new FixedSizeSlidingWindowMetrics(slidingWindowSize);
        this.minimumNumberOfCalls = Math
            .min(circuitBreakerConfig.getMinimumNumberOfCalls(), slidingWindowSize);
    } else {
        this.metrics = new SlidingTimeWindowMetrics(slidingWindowSize, clock);
        this.minimumNumberOfCalls = circuitBreakerConfig.getMinimumNumberOfCalls();
    }
    this.failureRateThreshold = circuitBreakerConfig.getFailureRateThreshold();
    this.slowCallRateThreshold = circuitBreakerConfig.getSlowCallRateThreshold();
    this.slowCallDurationThresholdInNanos = circuitBreakerConfig.getSlowCallDurationThreshold()
        .toNanos();
    this.numberOfNotPermittedCalls = new LongAdder();
}
 
Example 7
Source Project: vertx-micrometer-metrics   Source File: GaugesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreGaugeLabel() {
  MeterRegistry registry = new SimpleMeterRegistry();
  BackendRegistries.registerMatchers(registry, ALL_LABELS, Collections.singletonList(new Match()
    .setLabel("address")
    .setType(MatchType.REGEX)
    .setValue(".*")
    .setAlias("_")));
  Gauges<LongAdder> gauges = new Gauges<>("my_gauge", "", LongAdder::new, LongAdder::doubleValue, registry, Label.EB_ADDRESS);
  gauges.get("addr1").increment();
  gauges.get("addr1").increment();
  gauges.get("addr2").increment();

  Gauge g = registry.find("my_gauge").tags("address", "_").gauge();
  assertThat(g.value()).isEqualTo(3d);
  g = registry.find("my_gauge").tags("address", "addr1").gauge();
  assertThat(g).isNull();
  g = registry.find("my_gauge").tags("address", "addr2").gauge();
  assertThat(g).isNull();
}
 
Example 8
Source Project: reactor-core   Source File: MonoPeekAfterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void onAfterSuccessOrErrorFusion() {
	LongAdder invoked = new LongAdder();
	AtomicBoolean completedEmpty = new AtomicBoolean();
	AtomicReference<Throwable> error = new AtomicReference<>();

	@SuppressWarnings("deprecation")
	Mono<Integer> mono = Flux
			.range(1, 10)
			.reduce((a, b) -> a + b)
			.doAfterSuccessOrError((v, t) -> {
				if (v == null && t == null) completedEmpty.set(true);
				if (t != null) error.set(t);
				invoked.increment();
			});

	StepVerifier.create(mono.log())
	            .expectFusion()
	            .expectNext(55)
	            .expectComplete()
	            .verify();

	assertFalse("unexpected empty completion", completedEmpty.get());
	assertEquals(1, invoked.intValue());
	assertEquals("unexpected error", null, error.get());
}
 
Example 9
Source Project: jdk-source-analysis   Source File: LongAdderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    LongAdder adder = new LongAdder();
    int processors = Runtime.getRuntime().availableProcessors();
    System.out.println(processors);
    ExecutorService executor = Executors.newFixedThreadPool(processors);
    for (int i = 0; i < processors - 1; i++) {
        executor.execute(() -> {
            for (int j = 0; j < Integer.MAX_VALUE; j++) {
                adder.increment();
            }
        });
    }
    executor.execute(() -> {
        while (true) {
            try {
                System.out.println(adder.sum());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    executor.shutdown();
    LockSupport.park();
}
 
Example 10
Source Project: tlaplus   Source File: SimulationWorkerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testWorkerInterruption() throws Exception {
	ITool tool = new FastTool("", "BasicMultiTrace", "MCInv", new SimpleFilenameToStream());
	
	StateVec initStates = tool.getInitStates();
	ILiveCheck liveCheck =  new NoOpLiveCheck(tool, "BasicMultiTrace");
	BlockingQueue<SimulationWorkerResult> resultQueue = new LinkedBlockingQueue<>();
	
	// If we set the trace limit to the max, the worker should effectively run forever. We verify that after it generates
	// a result, we can cancel it and the worker will terminate.
	long traceNum = Long.MAX_VALUE;
	SimulationWorker worker = new SimulationWorker(0, tool, initStates, resultQueue, 0, 100, traceNum, false, null,
			liveCheck, new LongAdder(), new LongAdder());
	worker.start();
	
	// Check one result.
	SimulationWorkerResult res = resultQueue.take();
	
	assertTrue(res.isError());
	SimulationWorkerError err = res.error();
	assertEquals(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, err.errorCode);
	assertEquals(3, err.stateTrace.size());
	
	// Cancel the worker.
	worker.interrupt();
	worker.join();
	assertFalse(worker.isAlive());
}
 
Example 11
/**
 * A parallel unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCount() {
    LongAdder counter = new LongAdder();
    SplittableRandom r = new SplittableRandom();
    long size = 100;
    r.ints().limit(size).parallel().forEach(x -> {counter.increment();});
    assertEquals(counter.sum(), size);
}
 
Example 12
Source Project: reactor-core   Source File: StepVerifierTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void cancelOnUnexpectedNextWithMoreData() {
	LongAdder cancelled = new LongAdder();
	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(() -> StepVerifier.create(Flux.just("foo", "bar")
		                        .doOnCancel(cancelled::increment))
		            .expectNext("baz")
		            .expectComplete()
		            .verify())
	        .withMessageContaining("expected value: baz;");

	assertThat(cancelled.intValue())
			.overridingErrorMessage("the expectNext assertion didn't cause a cancellation")
	        .isEqualTo(1);
}
 
Example 13
Source Project: ignite   Source File: IgfsLocalMetrics.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds given numbers to read blocks counters.
 *
 * @param total Total number of blocks read.
 * @param secondary Number of blocks read form secondary FS.
 */
void addReadBlocks(int total, int secondary) {
    IgniteBiTuple<LongAdder, LongAdder> blocksRead0 = blocksRead;

    blocksRead0.get1().add(total);
    blocksRead0.get2().add(secondary);
}
 
Example 14
Source Project: jdk8u-dev-jdk   Source File: RandomTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * A parallel unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCount() {
    LongAdder counter = new LongAdder();
    Random r = new Random();
    long size = 100;
    r.doubles().limit(size).parallel().forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 15
/**
 * A sequential unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCountSeq() {
    LongAdder counter = new LongAdder();
    SplittableRandom r = new SplittableRandom();
    long size = 100;
    r.ints().limit(size).forEach(x -> {counter.increment();});
    assertEquals(counter.sum(), size);
}
 
Example 16
/**
 * A sequential unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCountSeq() {
    LongAdder counter = new LongAdder();
    SplittableRandom r = new SplittableRandom();
    long size = 100;
    r.ints().limit(size).forEach(x -> {counter.increment();});
    assertEquals(counter.sum(), size);
}
 
Example 17
Source Project: j2objc   Source File: ThreadLocalRandom8Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A sequential unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCountSeq() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).forEach(x -> counter.increment());
    assertEquals(size, counter.sum());
}
 
Example 18
Source Project: openjdk-jdk9   Source File: RandomTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * A sequential sized stream of longs generates the given number of values
 */
public void testLongsCount() {
    LongAdder counter = new LongAdder();
    Random r = new Random();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.longs(size).forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
 
Example 19
Source Project: MHAP   Source File: ClassicCounter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public long getCount(Object obj)
{
	LongAdder adder = map.get(obj);
	if (adder==null)
		return 0;
	
	return map.get(obj).longValue();
}
 
Example 20
Source Project: Bytecoder   Source File: ConcurrentSkipListMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds to element count, initializing adder if necessary
 *
 * @param c count to add
 */
private void addCount(long c) {
    LongAdder a;
    do {} while ((a = adder) == null &&
                 !ADDER.compareAndSet(this, null, a = new LongAdder()));
    a.add(c);
}
 
Example 21
Source Project: openjdk-jdk8u   Source File: RandomTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * A sequential sized stream of ints generates the given number of values
 */
public void testIntsCount() {
    LongAdder counter = new LongAdder();
    Random r = new Random();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.ints(size).forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
 
Example 22
/**
 * A parallel unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).parallel().forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 23
/**
 * A sequential unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCountSeq() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.ints().limit(size).forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 24
/**
 * A sequential unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCountSeq() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 25
/**
 * A parallel unsized stream of longs generates at least 100 values
 */
public void testUnsizedLongsCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.longs().limit(size).parallel().forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 26
/**
 * A parallel unsized stream of longs generates at least 100 values
 */
public void testUnsizedLongsCount() {
    LongAdder counter = new LongAdder();
    SplittableRandom r = new SplittableRandom();
    long size = 100;
    r.longs().limit(size).parallel().forEach(x -> {counter.increment();});
    assertEquals(counter.sum(), size);
}
 
Example 27
/**
 * A sequential unsized stream of doubles generates at least 100 values
 */
public void testUnsizedDoublesCountSeq() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 100;
    r.doubles().limit(size).forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example 28
Source Project: openjdk-jdk9   Source File: LongAdderTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    try {
        barrier.await();
        LongAdder a = adder;
        for (int i = 0; i < incs; ++i)
            a.add(1L);
        result = a.sum();
        barrier.await();
    } catch (Throwable t) { throw new Error(t); }
}
 
Example 29
/**
 * A parallel sized stream of ints generates the given number of values
 */
public void testIntsCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.ints(size).parallel().forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
 
Example 30
/**
 * A parallel unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCount() {
    LongAdder counter = new LongAdder();
    SplittableRandom r = new SplittableRandom();
    long size = 100;
    r.ints().limit(size).parallel().forEach(x -> {counter.increment();});
    assertEquals(counter.sum(), size);
}