Java Code Examples for java.util.concurrent.atomic.LongAdder#add()

The following examples show how to use java.util.concurrent.atomic.LongAdder#add() . 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: ApiTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Test
void retriesAfterTimeout() {
    final LoanApi mock = mock(LoanApi.class);
    final Api<LoanApi> api = new Api<>(mock);
    final String expected = UUID.randomUUID()
        .toString();
    final LongAdder adder = new LongAdder();
    final Function<LoanApi, String> function = (a) -> {
        adder.add(1);
        if (adder.intValue() > 2) {
            return expected;
        } else if (adder.intValue() == 2) {
            throw new ProcessingException(new IOException());
        } else {
            throw new ProcessingException(new SocketTimeoutException());
        }
    };
    final String result = api.call(function);
    assertThat(result).isSameAs(expected);
}
 
Example 2
Source File: RemoteFunctionClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Measures the occurrence of events in relation to the time having passed by since the last measurement. This is at minimum the value of
 * {@link #MEASUREMENT_INTERVAL}.
 *
 * @param eventCount A counter for the events having occurred so far within the current time-interval
 * @param lastMeasurementTime The point in time when the last measurement was done This reference will be updated in case the
 * time-interval was exceeded
 * @return The new current value for the dimension. If the time-interval was exceeded this is a newly calculated value otherwise the
 * return value is -1.
 */
protected final double measureDimension(LongAdder eventCount, AtomicLong lastMeasurementTime) {
  long now = Service.currentTimeMillis();
  long last = lastMeasurementTime.get();
  if (now - last > MEASUREMENT_INTERVAL) {
    //Only if this thread was the one setting the new measurement timestamp it may be the one resetting the event counter
    if (lastMeasurementTime.compareAndSet(last, now)) {
      long evtSum = eventCount.sum();
      //"Reset" the adder by subtracting the current evtSum (We can't use #reset() as this isn't thread safe)
      eventCount.add(-evtSum);
      //Calculate the new dimension value
      return (double) evtSum / ((double) (now - last) / 1000d);
    }
  }
  return -1;
}
 
Example 3
Source File: NioBookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public void uploadBookStream(@Suspended AsyncResponse response) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final byte[] buffer = new byte[4096];
    final LongAdder adder = new LongAdder();

    new NioReadEntity(
    // read handler                  
    in -> {
        final int n = in.read(buffer);
        if (n > 0) {
            adder.add(n);
            out.write(buffer, 0, n);
        }
    },
    // completion handler
    () -> {
        closeOutputStream(out);
        response.resume("Book Store uploaded: " + adder.longValue() + " bytes");
    }
    // by default the runtime will resume AsyncResponse with Throwable itself
    // if the error handler is not provided
    
    //,
    // error handler
    //t -> {
    //    response.resume(t);
    //}
    );
}
 
Example 4
Source File: Serial.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void testLongAdder() {
    LongAdder a = new LongAdder();
    a.add(45);
    LongAdder result = echo(a);
    if (result.longValue() != a.longValue())
        throw new RuntimeException("Unexpected longValue");

    checkSerialClassName(a, "java.util.concurrent.atomic.LongAdder$SerializationProxy");
}
 
Example 5
Source File: NumbersTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenBeanWithNegativeFields_shouldNotValidate() {
    Numbers numbers = new Numbers();

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

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

    Set<ConstraintViolation<Numbers>> constraintViolations = validator.validate(numbers);
    assertThat(constraintViolations.size()).isEqualTo(3);
}
 
Example 6
Source File: Serial.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testLongAdder() {
    LongAdder a = new LongAdder();
    a.add(45);
    LongAdder result = echo(a);
    if (result.longValue() != a.longValue())
        throw new RuntimeException("Unexpected longValue");

    checkSerialClassName(a, "java.util.concurrent.atomic.LongAdder$SerializationProxy");
}
 
Example 7
Source File: BucketCache.java    From hbase with Apache License 2.0 5 votes vote down vote up
public BucketEntry writeToCache(final IOEngine ioEngine, final BucketAllocator alloc,
    final LongAdder realCacheSize) throws IOException {
  int len = data.getSerializedLength();
  // This cacheable thing can't be serialized
  if (len == 0) {
    return null;
  }
  long offset = alloc.allocateBlock(len);
  boolean succ = false;
  BucketEntry bucketEntry = null;
  try {
    bucketEntry = new BucketEntry(offset, len, accessCounter, inMemory, RefCnt.create(recycler),
        getByteBuffAllocator());
    bucketEntry.setDeserializerReference(data.getDeserializer());
    if (data instanceof HFileBlock) {
      // If an instance of HFileBlock, save on some allocations.
      HFileBlock block = (HFileBlock) data;
      ByteBuff sliceBuf = block.getBufferReadOnly();
      ByteBuffer metadata = block.getMetaData();
      ioEngine.write(sliceBuf, offset);
      ioEngine.write(metadata, offset + len - metadata.limit());
    } else {
      // Only used for testing.
      ByteBuffer bb = ByteBuffer.allocate(len);
      data.serialize(bb, true);
      ioEngine.write(bb, offset);
    }
    succ = true;
  } finally {
    if (!succ) {
      alloc.freeBlock(offset);
    }
  }
  realCacheSize.add(len);
  return bucketEntry;
}
 
Example 8
Source File: LongAdderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * reset() causes subsequent sum() to return zero
 */
public void testReset() {
    LongAdder ai = new LongAdder();
    ai.add(2);
    assertEquals(2, ai.sum());
    ai.reset();
    assertEquals(0, ai.sum());
}
 
Example 9
Source File: NumbersTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenBeanWithPositiveFields_shouldNotValidate() {
    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(3);
}
 
Example 10
Source File: ConcurrentSkipListMap.java    From Bytecoder with 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 11
Source File: NumbersTest.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Test
public void givenBeanWithPositiveFields_shouldNotValidate() {
    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(3);
}
 
Example 12
Source File: Serial.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testLongAdder() {
    LongAdder a = new LongAdder();
    a.add(45);
    LongAdder result = echo(a);
    if (result.longValue() != a.longValue())
        throw new RuntimeException("Unexpected longValue");

    checkSerialClassName(a, "java.util.concurrent.atomic.LongAdder$SerializationProxy");
}
 
Example 13
Source File: CountersUtil.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add specified valut to the counter if supported, otherwise produce a warn.
 *
 * @param counter   counter
 * @param tablesKey tablesKey Type
 */
static void add(final @Nullable LongAdder counter, final @NonNull TablesKey tablesKey, final long amount) {
    if (counter != null) {
        counter.add(amount);
    } else {
        LOG.warn("Family {} not supported", tablesKey);
    }
}
 
Example 14
Source File: StatisticsInformation.java    From kafka-pubsub-emulator with Apache License 2.0 5 votes vote down vote up
public Float getErrorRating() {
  LongAdder totalMessages = new LongAdder();
  totalMessages.add(this.error.intValue());
  totalMessages.add(this.count.intValue());
  if (totalMessages.intValue() == 0) {
    return 0F;
  }
  return (this.error.floatValue() / totalMessages.floatValue()) * 100;
}
 
Example 15
Source File: CheckedConstraintsLogTest.java    From systemds with Apache License 2.0 5 votes vote down vote up
private EnumMap<PrivacyLevel,LongAdder> getMap(PrivacyLevel level, long value){
	EnumMap<PrivacyLevel,LongAdder> checked = new EnumMap<>(PrivacyLevel.class);
	LongAdder valueAdder = new LongAdder();
	valueAdder.add(value);
	checked.put(level, valueAdder);
	return checked;
}
 
Example 16
Source File: Serial.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void testLongAdder() {
    LongAdder a = new LongAdder();
    a.add(45);
    LongAdder result = echo(a);
    if (result.longValue() != a.longValue())
        throw new RuntimeException("Unexpected longValue");

    checkSerialClassName(a, "java.util.concurrent.atomic.LongAdder$SerializationProxy");
}
 
Example 17
Source File: Serial.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testLongAdder() {
    LongAdder a = new LongAdder();
    a.add(45);
    LongAdder result = echo(a);
    if (result.longValue() != a.longValue())
        throw new RuntimeException("Unexpected longValue");

    checkSerialClassName(a, "java.util.concurrent.atomic.LongAdder$SerializationProxy");
}
 
Example 18
Source File: BucketAllocator.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * Rebuild the allocator's data structures from a persisted map.
 * @param availableSpace capacity of cache
 * @param map A map stores the block key and BucketEntry(block's meta data
 *          like offset, length)
 * @param realCacheSize cached data size statistics for bucket cache
 * @throws BucketAllocatorException
 */
BucketAllocator(long availableSpace, int[] bucketSizes, Map<BlockCacheKey, BucketEntry> map,
    LongAdder realCacheSize) throws BucketAllocatorException {
  this(availableSpace, bucketSizes);

  // each bucket has an offset, sizeindex. probably the buckets are too big
  // in our default state. so what we do is reconfigure them according to what
  // we've found. we can only reconfigure each bucket once; if more than once,
  // we know there's a bug, so we just log the info, throw, and start again...
  boolean[] reconfigured = new boolean[buckets.length];
  int sizeNotMatchedCount = 0;
  int insufficientCapacityCount = 0;
  Iterator<Map.Entry<BlockCacheKey, BucketEntry>> iterator = map.entrySet().iterator();
  while (iterator.hasNext()) {
    Map.Entry<BlockCacheKey, BucketEntry> entry = iterator.next();
    long foundOffset = entry.getValue().offset();
    int foundLen = entry.getValue().getLength();
    int bucketSizeIndex = -1;
    for (int i = 0; i < this.bucketSizes.length; ++i) {
      if (foundLen <= this.bucketSizes[i]) {
        bucketSizeIndex = i;
        break;
      }
    }
    if (bucketSizeIndex == -1) {
      sizeNotMatchedCount++;
      iterator.remove();
      continue;
    }
    int bucketNo = (int) (foundOffset / bucketCapacity);
    if (bucketNo < 0 || bucketNo >= buckets.length) {
      insufficientCapacityCount++;
      iterator.remove();
      continue;
    }
    Bucket b = buckets[bucketNo];
    if (reconfigured[bucketNo]) {
      if (b.sizeIndex() != bucketSizeIndex) {
        throw new BucketAllocatorException("Inconsistent allocation in bucket map;");
      }
    } else {
      if (!b.isCompletelyFree()) {
        throw new BucketAllocatorException(
            "Reconfiguring bucket " + bucketNo + " but it's already allocated; corrupt data");
      }
      // Need to remove the bucket from whichever list it's currently in at
      // the moment...
      BucketSizeInfo bsi = bucketSizeInfos[bucketSizeIndex];
      BucketSizeInfo oldbsi = bucketSizeInfos[b.sizeIndex()];
      oldbsi.removeBucket(b);
      bsi.instantiateBucket(b);
      reconfigured[bucketNo] = true;
    }
    realCacheSize.add(foundLen);
    buckets[bucketNo].addAllocation(foundOffset);
    usedSize += buckets[bucketNo].getItemAllocationSize();
    bucketSizeInfos[bucketSizeIndex].blockAllocated(b);
  }

  if (sizeNotMatchedCount > 0) {
    LOG.warn("There are " + sizeNotMatchedCount + " blocks which can't be rebuilt because " +
      "there is no matching bucket size for these blocks");
  }
  if (insufficientCapacityCount > 0) {
    LOG.warn("There are " + insufficientCapacityCount + " blocks which can't be rebuilt - "
      + "did you shrink the cache?");
  }
}
 
Example 19
Source File: MonitorPlugin.java    From smart-socket with Apache License 2.0 4 votes vote down vote up
private long getAndReset(LongAdder longAdder) {
    long result = longAdder.longValue();
    longAdder.add(-result);
    return result;
}
 
Example 20
Source File: GPUMemoryManager.java    From systemds with Apache License 2.0 3 votes vote down vote up
/**
 * Convenient method to add misc timers
 * 
 * @param opcode opcode
 * @param globalGPUTimer member of GPUStatistics
 * @param globalGPUCounter member of GPUStatistics
 * @param instructionLevelTimer member of GPUInstruction
 * @param startTime start time
 */
private static void addMiscTime(String opcode, LongAdder globalGPUTimer, LongAdder globalGPUCounter, String instructionLevelTimer, long startTime) {
	if(DMLScript.STATISTICS) {
		long totalTime = System.nanoTime() - startTime;
		globalGPUTimer.add(totalTime);
		globalGPUCounter.add(1);
	}
}