java.util.concurrent.atomic.LongAdder Java Examples

The following examples show how to use java.util.concurrent.atomic.LongAdder. 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 File: MonoPeekAfterTest.java    From reactor-core with 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 #2
Source File: LongAdderTest.java    From jdk-source-analysis with 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 #3
Source File: GaugesTest.java    From vertx-micrometer-metrics with 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 #4
Source File: CircuitBreakerMetrics.java    From resilience4j with 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 #5
Source File: FluxBufferPredicateTest.java    From reactor-core with 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 File: MonoPeekAfterTest.java    From reactor-core with 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 #7
Source File: HBaseRollForward.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #8
Source File: SimulationWorkerTest.java    From tlaplus with 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 #9
Source File: MonoPeekAfterTest.java    From reactor-core with 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 #10
Source File: NumbersTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenBeanWithNegativeFields_shouldValidate(){

    Numbers numbers = new Numbers();

    numbers.setABigDecimal(BigDecimal.valueOf(-5));
    numbers.setAPrimitiveNumber(-5);

    LongAdder longAdder = new LongAdder();
    longAdder.add(-5);
    numbers.setALongAdder(longAdder);

    Set<ConstraintViolation<Numbers>> constraintViolations = validator.validate(numbers);
    assertThat(constraintViolations.size()).isEqualTo(0);
}
 
Example #11
Source File: ConsumerStatsRecorderImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public ConsumerStatsRecorderImpl() {
    numMsgsReceived = new LongAdder();
    numBytesReceived = new LongAdder();
    numReceiveFailed = new LongAdder();
    numBatchReceiveFailed = new LongAdder();
    numAcksSent = new LongAdder();
    numAcksFailed = new LongAdder();
    totalMsgsReceived = new LongAdder();
    totalBytesReceived = new LongAdder();
    totalReceiveFailed = new LongAdder();
    totalBatchReceiveFailed = new LongAdder();
    totalAcksSent = new LongAdder();
    totalAcksFailed = new LongAdder();
}
 
Example #12
Source File: MonotonicCounterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void expire() throws Exception {
  WeakReference<LongAdder> ref = new WeakReference<>(
    PolledMeter.using(registry).withId(id).monitorMonotonicCounter(new LongAdder()));
  while (ref.get() != null) {
    System.gc();
  }

  Assertions.assertEquals(1, registry.state().size());
  update();
  Assertions.assertEquals(0, registry.state().size());
}
 
Example #13
Source File: ThreadLocalRandomTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #14
Source File: SimulationWorkerTest.java    From tlaplus with 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 #15
Source File: ThreadLocalRandomTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #16
Source File: SplittableRandomTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: FederatedResponse.java    From systemds with Apache License 2.0 5 votes vote down vote up
/**
 * Set checked privacy constraints in response if the provided map is not empty.
 * If the map is empty, it means that no privacy constraints were found.
 * @param checkedConstraints map of checked constraints from the PrivacyMonitor
 */
public void setCheckedConstraints(Map<PrivacyLevel,LongAdder> checkedConstraints){
	if ( checkedConstraints != null && !checkedConstraints.isEmpty() ){
		this.checkedConstraints = new EnumMap<PrivacyLevel, LongAdder>(PrivacyLevel.class);
		this.checkedConstraints.putAll(checkedConstraints);
	}	
}
 
Example #18
Source File: SplittableRandomTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: RandomTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A parallel unsized stream of ints generates at least 100 values
 */
public void testUnsizedIntsCount() {
    LongAdder counter = new LongAdder();
    Random r = new Random();
    long size = 100;
    r.ints().limit(size).parallel().forEach(x -> {
        counter.increment();
    });
    assertEquals(counter.sum(), size);
}
 
Example #20
Source File: FluxDoOnEachTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void fusedAsync() {
	AtomicReference<String> onNext = new AtomicReference<>();
	AtomicReference<Throwable> onError = new AtomicReference<>();
	AtomicBoolean onComplete = new AtomicBoolean();
	LongAdder state = new LongAdder();

	StepVerifier.create(Flux.just("foo")
	                        .publishOn(Schedulers.immediate())
	                        .map(s -> s + "_async")
	                        .doOnEach(s -> {
		                        if (s.isOnNext()) {
			                        onNext.set(s.get());
			                        state.increment();
		                        }
		                        else if (s.isOnError()) {
			                        onError.set(s.getThrowable());
		                        }
		                        else if (s.isOnComplete()) {
			                        onComplete.set(true);
		                        }
	                        }))
	            .expectFusion(Fuseable.ASYNC, Fuseable.ASYNC)
	            .expectNext("foo_async")
	            .verifyComplete();

	assertThat(onNext).hasValue("foo_async");
	assertThat(onError).hasValue(null);
	assertThat(onComplete).isTrue();
}
 
Example #21
Source File: ThreadLocalRandomTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A parallel sized stream of longs generates the given number of values
 */
public void testLongsCount() {
    LongAdder counter = new LongAdder();
    ThreadLocalRandom r = ThreadLocalRandom.current();
    long size = 0;
    for (int reps = 0; reps < REPS; ++reps) {
        counter.reset();
        r.longs(size).parallel().forEach(x -> {
            counter.increment();
        });
        assertEquals(counter.sum(), size);
        size += 524959;
    }
}
 
Example #22
Source File: ThreadLocalRandomTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #23
Source File: ThreadLocalRandomTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: NumbersTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenBeanWithZeroFields_shouldValidate() {
    Numbers numbers = new Numbers();

    numbers.setABigDecimal(BigDecimal.ZERO);
    numbers.setAPrimitiveNumber(0);

    LongAdder longAdder = new LongAdder();
    longAdder.add(0);
    numbers.setALongAdder(longAdder);

    Set<ConstraintViolation<Numbers>> constraintViolations = validator.validate(numbers);
    assertThat(constraintViolations.size()).isEqualTo(0);
}
 
Example #25
Source File: LongAdderDemo.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    phaser.arriveAndAwaitAdvance();
    phaser.arriveAndAwaitAdvance();
    LongAdder a = adder;
    for (int i = 0; i < incs; ++i)
        a.increment();
    result = a.sum();
    phaser.arrive();
}
 
Example #26
Source File: MetricsCounter.java    From ratelimiter4j with Apache License 2.0 5 votes vote down vote up
public MetricsCounter() {
  int length = MetricType.values().length;
  counters = new LongAdder[length];
  for (int i = 0; i < length; i++) {
    counters[i] = new LongAdder();
  }
}
 
Example #27
Source File: SplittableRandomTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #28
Source File: IgfsLocalMetrics.java    From ignite with 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 #29
Source File: SplittableRandomTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #30
Source File: EffectiveRibInWriter.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public long getPrefixedReceivedCount(final TablesKey tablesKey) {
    final LongAdder counter = this.prefixesReceived.get(tablesKey);
    if (counter == null) {
        return 0;
    }
    return counter.longValue();
}