java.util.concurrent.atomic.LongAdder#add()源码实例Demo

下面列出了java.util.concurrent.atomic.LongAdder#add() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: xyz-hub   文件: RemoteFunctionClient.java
/**
 * 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;
}
 
源代码2 项目: robozonky   文件: ApiTest.java
@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);
}
 
源代码3 项目: dragonwell8_jdk   文件: Serial.java
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");
}
 
源代码4 项目: jdk8u60   文件: Serial.java
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");
}
 
源代码5 项目: systemds   文件: CheckedConstraintsLogTest.java
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;
}
 
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;
}
 
源代码7 项目: bgpcep   文件: CountersUtil.java
/**
 * 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);
    }
}
 
源代码8 项目: jdk8u-jdk   文件: Serial.java
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");
}
 
源代码9 项目: Java-EE-8-Sampler   文件: NumbersTest.java
@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);
}
 
源代码10 项目: cxf   文件: NioBookStore.java
@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);
    //}
    );
}
 
源代码11 项目: Bytecoder   文件: ConcurrentSkipListMap.java
/**
 * 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);
}
 
源代码12 项目: Java-EE-8-Sampler   文件: NumbersTest.java
@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);
}
 
源代码13 项目: j2objc   文件: LongAdderTest.java
/**
 * 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());
}
 
源代码14 项目: hbase   文件: BucketCache.java
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;
}
 
源代码15 项目: jdk8u-dev-jdk   文件: Serial.java
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");
}
 
源代码16 项目: Java-EE-8-Sampler   文件: NumbersTest.java
@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);
}
 
源代码17 项目: openjdk-8   文件: Serial.java
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");
}
 
源代码18 项目: smart-socket   文件: MonitorPlugin.java
private long getAndReset(LongAdder longAdder) {
    long result = longAdder.longValue();
    longAdder.add(-result);
    return result;
}
 
源代码19 项目: hbase   文件: BucketAllocator.java
/**
 * 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?");
  }
}
 
源代码20 项目: systemds   文件: GPUMemoryManager.java
/**
 * 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);
	}
}