Java Code Examples for com.codahale.metrics.Counter#dec()

The following examples show how to use com.codahale.metrics.Counter#dec() . 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: MetricTypesExample.java    From semantic-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * A counter is just a gauge for an AtomicLong instance. You can increment or decrement its
 * value. We want a more efficient way of measuring the pending job in a queue
 */
private static void reportCounter() {
    // Create or fetch (if it is already created) the metric.
    final Counter counter = registry.counter(APP_PREFIX.tagged("what", "job-count"));

    // Somewhere in your code where you are adding new jobs to the queue you increment the
    // counter as well
    counter.inc();

    // Oh look! Another job!
    counter.inc();

    // Somewhere in your code the job is going to be removed from the queue you decrement the
    // counter
    counter.dec();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, the current value of the counter will be read
    // and
    // a datapoint will be created and reported.
}
 
Example 2
Source File: TCPMetricsImpl.java    From vertx-dropwizard-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void disconnected(Long ctx, SocketAddress remoteAddress) {
  openConnections.dec();
  connections.update(System.nanoTime() - ctx, TimeUnit.NANOSECONDS);

  // On network outage the remoteAddress can be null.
  // Do not report the open-connections when it's null
  if (remoteAddress != null) {
    // Remote address connection metrics
    Counter counter = counter("open-connections", remoteAddress.host());
    counter.dec();
    if (counter.getCount() == 0) {
      remove("open-connections", remoteAddress.host());
    }
  }

  // A little clunky, but it's possible we got here after closed has been called
  if (closed) {
    removeAll();
  }
}
 
Example 3
Source File: StatsCollector.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public long getRegionBytesWritten(final Region region, final boolean reset) {
    final Counter counter = KVMetrics.counter(KVMetricNames.REGION_BYTES_WRITTEN, String.valueOf(region.getId()));
    final long value = counter.getCount();
    if (reset) {
        counter.dec(value);
    }
    return value;
}
 
Example 4
Source File: StatsCollector.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public long getRegionBytesRead(final Region region, final boolean reset) {
    final Counter counter = KVMetrics.counter(KVMetricNames.REGION_BYTES_READ, String.valueOf(region.getId()));
    final long value = counter.getCount();
    if (reset) {
        counter.dec(value);
    }
    return value;
}
 
Example 5
Source File: StatsCollector.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public long getRegionKeysWritten(final Region region, final boolean reset) {
    final Counter counter = KVMetrics.counter(KVMetricNames.REGION_KEYS_WRITTEN, String.valueOf(region.getId()));
    final long value = counter.getCount();
    if (reset) {
        counter.dec(value);
    }
    return value;
}
 
Example 6
Source File: StatsCollector.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public long getRegionKeysRead(final Region region, final boolean reset) {
    final Counter counter = KVMetrics.counter(KVMetricNames.REGION_KEYS_READ, String.valueOf(region.getId()));
    final long value = counter.getCount();
    if (reset) {
        counter.dec(value);
    }
    return value;
}
 
Example 7
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected static void processCounter(@NotNull Counter counter, long delta) {
    if (delta > 0) {
        counter.inc(delta);
    }
    else if (delta < 0) {
        counter.dec(delta * -1);
    }
}
 
Example 8
Source File: DropWizardMetricsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void collect_Counter() {
  // create dropwizard metrics
  Counter evictions = metricRegistry.counter("cache_evictions");
  evictions.inc();
  evictions.inc(3);
  evictions.dec();
  evictions.dec(2);

  ArrayList<Metric> metrics = new ArrayList<>(dropWizardMetrics.getMetrics());
  assertThat(metrics.size()).isEqualTo(1);

  assertThat(metrics.get(0).getMetricDescriptor())
      .isEqualTo(
          MetricDescriptor.create(
              "codahale_cache_evictions_counter",
              "Collected from codahale (metric=cache_evictions, "
                  + "type=com.codahale.metrics.Counter)",
              DEFAULT_UNIT,
              Type.GAUGE_INT64,
              Collections.<LabelKey>emptyList()));
  assertThat(metrics.get(0).getTimeSeriesList().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getLabelValues().size()).isEqualTo(0);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().get(0).getValue())
      .isEqualTo(Value.longValue(1));
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getStartTimestamp()).isNull();
}
 
Example 9
Source File: SubscriptionStreamController.java    From nakadi with MIT License 5 votes vote down vote up
private StreamingResponseBody stream(final String subscriptionId,
                                     final HttpServletRequest request,
                                     final HttpServletResponse response,
                                     final Client client,
                                     final StreamParameters streamParameters,
                                     final Span parentSubscriptionSpan) {
    final String flowId = FlowIdUtils.peek();

    return outputStream -> {
        FlowIdUtils.push(flowId);
        final String metricName = metricNameForSubscription(subscriptionId, CONSUMERS_COUNT_METRIC_NAME);
        final Counter consumerCounter = metricRegistry.counter(metricName);
        consumerCounter.inc();
        final AtomicBoolean connectionReady = closedConnectionsCrutch.listenForConnectionClose(request);
        SubscriptionStreamer streamer = null;
        final SubscriptionOutputImpl output = new SubscriptionOutputImpl(response, outputStream);
        try {
            if (eventStreamChecks.isSubscriptionConsumptionBlocked(subscriptionId, client.getClientId())) {
                writeProblemResponse(response, outputStream,
                        Problem.valueOf(FORBIDDEN, "Application or event type is blocked"));
                return;
            }
            final Subscription subscription = subscriptionDbRepository.getSubscription(subscriptionId);
            subscriptionValidationService.validatePartitionsToStream(subscription,
                    streamParameters.getPartitions());
            streamer = subscriptionStreamerFactory.build(subscription, streamParameters, output,
                    connectionReady, parentSubscriptionSpan, client.getClientId());
            streamer.stream();
        } catch (final InterruptedException ex) {
            LOG.warn("Interrupted while streaming with " + streamer, ex);
            Thread.currentThread().interrupt();
        } catch (final RuntimeException e) {
            output.onException(e);
        } finally {
            consumerCounter.dec();
            outputStream.close();
        }
    };
}
 
Example 10
Source File: MetricsConfigurator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static boolean resetCounter(MetricRegistry metrics, String name) {
  Counter counter = getCounter(metrics, name);
  boolean result = false;
  if(counter != null) {
    //there could be race condition with observer thread trying to update the counter. This should be ok.
    counter.dec(counter.getCount());
    result = true;
  }
  return result;
}
 
Example 11
Source File: CountedHandler.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Counter counter = metricRegistry.counter(counterName);
    counter.inc();

    try {
        routeHandler.handle(routeContext);
    } finally {
        if (isActive) {
            counter.dec();
        }
    }
}
 
Example 12
Source File: CountedInterceptor.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
private Object countedCallable(InvocationContext context, Executable executable) throws Exception {
    MetricResolver.Of<Counted> counted = resolver.counted(bean.getBeanClass(), executable);
    Counter counter = (Counter) registry.getMetrics().get(counted.metricName());
    if (counter == null)
        throw new IllegalStateException("No counter with name [" + counted.metricName() + "] found in registry [" + registry + "]");

    counter.inc();
    try {
        return context.proceed();
    } finally {
        if (!counted.metricAnnotation().monotonic())
            counter.dec();
    }
}
 
Example 13
Source File: TitanOperationCountingTest.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
private void resetEdgeCacheCounts() {
    Counter counter = metric.getCounter(metricsPrefix, EDGESTORE_NAME + METRICS_CACHE_SUFFIX, CacheMetricsAction.RETRIEVAL.getName());
    counter.dec(counter.getCount());
    counter = metric.getCounter(metricsPrefix, EDGESTORE_NAME + METRICS_CACHE_SUFFIX, CacheMetricsAction.MISS.getName());
    counter.dec(counter.getCount());
}
 
Example 14
Source File: TestReplicasClient.java    From hbase with Apache License 2.0 4 votes vote down vote up
@Test
public void testHedgedRead() throws Exception {
  byte[] b1 = Bytes.toBytes("testHedgedRead");
  openRegion(hriSecondary);

  try {
    // A simple put works, even if there here a second replica
    Put p = new Put(b1);
    p.addColumn(f, b1, b1);
    table.put(p);
    LOG.info("Put done");

    // A get works and is not stale
    Get g = new Get(b1);
    Result r = table.get(g);
    Assert.assertFalse(r.isStale());
    Assert.assertFalse(r.getColumnCells(f, b1).isEmpty());
    LOG.info("get works and is not stale done");

    //reset
    AsyncConnectionImpl conn = (AsyncConnectionImpl) HTU.getConnection().toAsyncConnection();
    Counter hedgedReadOps = conn.getConnectionMetrics().get().hedgedReadOps;
    Counter hedgedReadWin = conn.getConnectionMetrics().get().hedgedReadWin;
    hedgedReadOps.dec(hedgedReadOps.getCount());
    hedgedReadWin.dec(hedgedReadWin.getCount());

    // Wait a little on the main region, just enough to happen once hedged read
    // and hedged read did not returned faster
    long primaryCallTimeoutNs = conn.connConf.getPrimaryCallTimeoutNs();
    // The resolution of our timer is 10ms, so we need to sleep a bit more otherwise we may not
    // trigger the hedged read...
    SlowMeCopro.sleepTime.set(TimeUnit.NANOSECONDS.toMillis(primaryCallTimeoutNs) + 100);
    SlowMeCopro.getSecondaryCdl().set(new CountDownLatch(1));
    g = new Get(b1);
    g.setConsistency(Consistency.TIMELINE);
    r = table.get(g);
    Assert.assertFalse(r.isStale());
    Assert.assertFalse(r.getColumnCells(f, b1).isEmpty());
    Assert.assertEquals(1, hedgedReadOps.getCount());
    Assert.assertEquals(0, hedgedReadWin.getCount());
    SlowMeCopro.sleepTime.set(0);
    SlowMeCopro.getSecondaryCdl().get().countDown();
    LOG.info("hedged read occurred but not faster");


    // But if we ask for stale we will get it and hedged read returned faster
    SlowMeCopro.getPrimaryCdl().set(new CountDownLatch(1));
    g = new Get(b1);
    g.setConsistency(Consistency.TIMELINE);
    r = table.get(g);
    Assert.assertTrue(r.isStale());
    Assert.assertTrue(r.getColumnCells(f, b1).isEmpty());
    Assert.assertEquals(2, hedgedReadOps.getCount());
    // we update the metrics after we finish the request so we use a waitFor here, use assert
    // directly may cause failure if we run too fast.
    HTU.waitFor(10000, () -> hedgedReadWin.getCount() == 1);
    SlowMeCopro.getPrimaryCdl().get().countDown();
    LOG.info("hedged read occurred and faster");

  } finally {
    SlowMeCopro.getPrimaryCdl().get().countDown();
    SlowMeCopro.getSecondaryCdl().get().countDown();
    SlowMeCopro.sleepTime.set(0);
    Delete d = new Delete(b1);
    table.delete(d);
    closeRegion(hriSecondary);
  }
}