Java Code Examples for com.codahale.metrics.Timer.Context#stop()

The following examples show how to use com.codahale.metrics.Timer.Context#stop() . 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: FrontierManager.java    From ache with Apache License 2.0 6 votes vote down vote up
public LinkRelevance nextURL(boolean asyncLoad) throws FrontierPersistentException, DataNotFoundException {
    Context timerContext = selectTimer.time();
    try {
        LinkRelevance link = scheduler.nextLink(asyncLoad);
        if (link == null) {
            if (scheduler.hasPendingLinks()) {
                throw new DataNotFoundException(false, "No links available for selection right now.");
            } else {
                throw new DataNotFoundException(true, "Frontier run out of links.");
            }
        }
        frontier.delete(link);

        schedulerLog.printf("%d\t%.5f\t%s\n", System.currentTimeMillis(),
                            link.getRelevance(), link.getURL().toString());
        return link;
    } finally {
        timerContext.stop();
    }
}
 
Example 2
Source File: CassandraAuditor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void upsert (String id, Instant rxTimestamp, String eventLog) {
    BoundStatement statement = new BoundStatement(upsert).bind(
            Date.from(Instant.now()),		// Time the event is written to the log
            eventLog,						// Composite event log message (state, notification, error message, etc.)
            id,                       // Notification id that event belongs to (i.e., person:<uuid>, place:<uuid>)
            Date.from(rxTimestamp)
            );

    Context timer = auditDbTimer.time();
    session.execute(statement);
    timer.stop();

    LOGGER.debug(eventLog);
}
 
Example 3
Source File: RecurlyCallbackHttpHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public TemplatedResponse doHandle(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
   Context timer = WEBHOOK_TIMER.time();
   
   try{
      String recurlyXML = request.content().toString(CharsetUtil.UTF_8);
      Document document = XMLHelper.parse(recurlyXML);
      String transactionType = document.getDocumentElement().getTagName();
      WebhookHandler<? extends Object>handler=handlers.get(transactionType);
      
      if(transactionType.equals(TRANS_TYPE_CLOSED_INVOICE_NOTIFICATION)){
         ClosedInvoiceNotification notification = XMLHelper.unmarshall(document,ClosedInvoiceNotification.class);
        ((WebhookHandler)handler).handleWebhook(notification);
      }
      else{
         IGNORED_COUNTER.inc();
         LOGGER.info(MSG_IGNORE_NOTIFICATION);
      }
      return createTemplateResponse(HttpResponseStatus.NO_CONTENT);
   }
   catch(Exception e){
      ERRORED_COUNTER.inc();
      LOGGER.error("Unknown error processing recurly webhook",e);
      return createTemplateResponse(HttpResponseStatus.BAD_REQUEST);
   }
   finally{
      timer.stop();
   }
}
 
Example 4
Source File: TestDbPool.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Test
public void testOpenCloseConnections() throws SQLException {
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        Context context = timer.time();
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        stmt.executeQuery("select * from city");
        conn.close();
        context.stop();
    }
    logReporter.report();
   
   	}
 
Example 5
Source File: TestDbPool.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Test
public void testOpenCloseConnections() throws SQLException {
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        Context context = timer.time();
        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        stmt.executeQuery("select * from city");
        conn.close();
        context.stop();
    }
    logReporter.report();
   
   	}
 
Example 6
Source File: MetricTypesExample.java    From semantic-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * A timer measures both the rate that a particular piece of code is called and the distribution
 * of its duration. For example we want to measure the rate and handling duration of incoming
 * requests.
 */
private static void reportTimer() {
    // Create or fetch (if it is already created) the metric.
    final Timer timer = registry.timer(
        APP_PREFIX.tagged("what", "incoming-request-time").tagged("endpoint", "/v1/get_stuff"));

    // Do this before starting to do the thing. This creates a measurement context object
    // that you can pass around.
    final Context context = timer.time();

    // Do stuff that takes time (e.g., process the request)
    try {
        Thread.sleep(100);
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }

    // Tell the context that it's done. This will register the duration and counts one
    // occurrence.
    context.stop();

    // 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, different stats and aggregations (all the
    // stats that you would get from a meter and a histogram are included) will be calculated
    // and
    // datapoints will be created and reported.
}
 
Example 7
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, R> R timed(@NotNull Function<T, R> f, T arg, @NotNull String timerName) {
    final Context context = getNamedTimer(timerName).time();
    try {
        return f.apply(arg);
    }
    finally {
        context.stop();
    }

}
 
Example 8
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <V> V timed(@NotNull Callable<V> c, @NotNull String timerName) throws Exception {
    final Context context = getNamedTimer(timerName).time();
    try {
        return c.call();
    }
    finally {
        context.stop();
    }
}
 
Example 9
Source File: HttpDownloader.java    From ache with Apache License 2.0 5 votes vote down vote up
private void doHandle() {
    if (callback != null) {
        Context context = handlerTimer.time();
        try {
            if (exception != null) {
                callback.failed(link, exception);
            } else {
                callback.completed(link, response);
            }
        } finally {
            context.stop();
        }
    }
}
 
Example 10
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, U> void timed(@NotNull BiConsumer<T, U> bc, T arg1, U arg2, @NotNull String timerName) {
    final Context context = getNamedTimer(timerName).time();
    try {
        bc.accept(arg1, arg2);
    }
    finally {
        context.stop();
    }
}
 
Example 11
Source File: CodahaleMetricsCollector.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public <T, U, R> R timed(@NotNull BiFunction<T, U, R> bf, T arg1, U arg2, @NotNull String timerName) {
    final Context context = getNamedTimer(timerName).time();
    try {
        return bf.apply(arg1, arg2);
    }
    finally {
        context.stop();
    }

}
 
Example 12
Source File: DropwizardMetrics.java    From astrix with Apache License 2.0 5 votes vote down vote up
@Override
public <T> CheckedCommand<T> timeExecution(final CheckedCommand<T> execution) {
	return () -> {
		Context context = timer.time();
		try {
			return execution.call();
		} finally {
			context.stop();
		}
	};
}
 
Example 13
Source File: RequestMetrics.java    From helios with Apache License 2.0 4 votes vote down vote up
public void userError(Context context) {
  userError();
  context.stop();
}
 
Example 14
Source File: RequestMetrics.java    From helios with Apache License 2.0 4 votes vote down vote up
public void failure(Context context) {
  failure();
  context.stop();
}
 
Example 15
Source File: RequestMetrics.java    From helios with Apache License 2.0 4 votes vote down vote up
public void success(Context context) {
  success();
  context.stop();
}
 
Example 16
Source File: EndpointService.java    From hawkular-agent with Apache License 2.0 4 votes vote down vote up
/**
 * Discovers all resources, puts them in the {@link #resourceManager},
 * and triggers any listeners listening for new inventory.
 *
 * This will look for all root resources (resources whose types are that of the root resource types
 * as defined by {@link ResourceTypeManager#getRootResourceTypes()} and then obtain all their
 * children (recursively down to all descendents). Effectively, this discovers the full
 * resource hierarchy.
 *
 * This method does not block - it runs the discovery in another thread.
 */
public void discoverAll() {
    status.assertRunning(getClass(), "discoverAll()");

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            WriteLock lock = EndpointService.this.discoveryScanRWLock.writeLock();
            lock.lock();
            try {
                DiscoveryResults discoveryResults = new DiscoveryResults();

                LOG.infoDiscoveryRequested(getMonitoredEndpoint());
                long duration = -1;
                try (S session = openSession()) {
                    Set<ResourceType<L>> rootTypes = getResourceTypeManager().getRootResourceTypes();
                    Context timer = getDiagnostics().getFullDiscoveryScanTimer().time();
                    for (ResourceType<L> rootType : rootTypes) {
                        discoverChildren(null, rootType, session, discoveryResults);
                    }
                    long nanos = timer.stop();
                    duration = TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS);
                } catch (Exception e) {
                    LOG.errorCouldNotAccess(EndpointService.this, e);
                    discoveryResults.error(e);
                }

                getResourceManager().logTreeGraph("Discovered all resources for: " + getMonitoredEndpoint(),
                        duration);

                discoveryResults.discoveryFinished();
            } finally {
                lock.unlock();
            }
        }
    };

    try {
        this.fullDiscoveryScanThreadPool.execute(runnable);
    } catch (RejectedExecutionException ree) {
        LOG.debugf("Redundant full discovery scan will be ignored for endpoint [%s]", getMonitoredEndpoint());
    }
}
 
Example 17
Source File: SingularityUploader.java    From Singularity with Apache License 2.0 4 votes vote down vote up
int uploadBatch(List<Path> toUpload) {
  final long start = System.currentTimeMillis();
  LOG.info("{} Uploading {} item(s)", logIdentifier, toUpload.size());

  int success = 0;

  for (int i = 0; i < toUpload.size(); i++) {
    final Context context = metrics.getUploadTimer().time();
    final Path file = toUpload.get(i);
    if (
      !configuration.isCheckForOpenFiles() ||
      uploadMetadata.isImmediate() ||
      !isFileOpen(file, configuration.isCheckOpenFilesViaFuser())
    ) {
      try {
        uploadSingle(i, file);
        metrics.upload();
        success++;
        Files.delete(file);
      } catch (RetryException re) {
        metrics.error();
        LOG.warn("{} Couldn't upload or delete {}", logIdentifier, file, re);
        exceptionNotifier.notify(
          String.format("%s exception during upload", re.getCause().getClass()),
          re.getCause(),
          ImmutableMap.of(
            "logIdentifier",
            logIdentifier,
            "file",
            file.toString(),
            "failedAttempts",
            Integer.toString(re.getNumberOfFailedAttempts())
          )
        );
      } catch (Exception e) {
        metrics.error();
        LOG.warn("{} Couldn't upload or delete {}", logIdentifier, file, e);
        exceptionNotifier.notify(
          String.format("Error during upload (%s)", e.getMessage()),
          e,
          ImmutableMap.of("logIdentifier", logIdentifier, "file", file.toString())
        );
      } finally {
        context.stop();
      }
    } else {
      LOG.debug("{} is in use by another process, will retry upload later", file);
    }
  }

  LOG.info(
    "{} Uploaded {} out of {} item(s) in {}",
    logIdentifier,
    success,
    toUpload.size(),
    JavaUtils.duration(start)
  );
  return toUpload.size();
}
 
Example 18
Source File: TestKafkaUReplicatorMetricsReporter.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultConf() {

  KafkaUReplicatorMetricsReporter.init(null);
  Assert.assertNull(KafkaUReplicatorMetricsReporter.get().getRegistry());
  try {
    Field field = KafkaUReplicatorMetricsReporter.class.getDeclaredField("DID_INIT");
    field.setAccessible(true);
    field.set(KafkaUReplicatorMetricsReporter.get(), false);
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  MetricsReporterConf conf = new MetricsReporterConf("sjc1.sjc1a",
      Collections.singletonList("ureplicator-manager"), null, "localhost",
      4744);
  KafkaUReplicatorMetricsReporter.init(conf);
  Object firstInitInstance = KafkaUReplicatorMetricsReporter.get();
  // Double init will get same instance.
  KafkaUReplicatorMetricsReporter.init(conf);
  Object secondInitInstance = KafkaUReplicatorMetricsReporter.get();
  Assert.assertTrue(firstInitInstance == secondInitInstance);
  Counter testCounter0 = new Counter();
  Meter testMeter0 = new Meter();
  Timer testTimer0 = new Timer();
  KafkaUReplicatorMetricsReporter.get().registerMetric("testCounter0", testCounter0);
  KafkaUReplicatorMetricsReporter.get().registerMetric("testMeter0", testMeter0);
  KafkaUReplicatorMetricsReporter.get().registerMetric("testTimer0", testTimer0);

  testCounter0.inc();
  testMeter0.mark();
  Context context = testTimer0.time();
  context.stop();

  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getCounters().get("testCounter0")
          .getCount(),
      1);
  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getMeters().get("testMeter0")
          .getCount(),
      1);
  Assert.assertEquals(
      KafkaUReplicatorMetricsReporter.get().getRegistry().getTimers().get("testTimer0")
          .getCount(),
      1);
}
 
Example 19
Source File: CassandraHistoryAppenderDao.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected void doAppend(HistoryLogEntry event) {
   List<Object> values = new ArrayList<Object>(HistoryTable.COLUMN_COUNT);
   PreparedStatement stmt;

   Context metricsTimer = null;
   
   try{
      switch (event.getType()) {
      case CRITICAL_PLACE_LOG:
         stmt = criticalPlaceTable.insert();
         values.add(event.getId());
         metricsTimer = criticalPlaceLogTimer.time();
         break;
      case DETAILED_PLACE_LOG:
         stmt = detailedPlaceTable.insert();
         values.add(event.getId());
         metricsTimer = detailedPlaceLogTimer.time(); 
         break;
      case DETAILED_PERSON_LOG:
         stmt = detailedPersonTable.insert();
         values.add(event.getId());
         metricsTimer = detailedPersonLogTimer.time();
         break;
      case DETAILED_DEVICE_LOG:
         stmt = detailedDeviceTable.insert();
         values.add(event.getId());
         metricsTimer = detailedDeviceLogTimer.time();
         break;
      case DETAILED_HUB_LOG:
          stmt = detailedHubTable.insert();
          values.add(event.getId());
          metricsTimer = detailedHubLogTimer.time();
          break;
      case DETAILED_RULE_LOG:
         stmt = detailedRuleTable.insert();
         CompositeId<UUID, Integer> rid = (CompositeId<UUID, Integer>) event.getId();
         values.add(rid.getPrimaryId());
         values.add(rid.getSecondaryId());
         metricsTimer = detailedRuleLogTimer.time();
         break;
      case DETAILED_SUBSYSTEM_LOG:
         stmt = detailedSubsystemTable.insert();
         CompositeId<UUID, String> sid = (CompositeId<UUID, String>) event.getId();
         values.add(sid.getPrimaryId());
         values.add(sid.getSecondaryId());
         metricsTimer = detailedSubsystemLogTimer.time();
         break;
      case DETAILED_ALARM_LOG:
         stmt = detailedAlarmTable.insert();
         values.add(event.getId());
         metricsTimer = detailedAlarmLogTimer.time();
         break;
      default:
         throw new IllegalArgumentException("Unsupported log type:" + event.getType());
      }
      values.add(nextTimeUuid(event.getTimestamp()));
      values.add(event.getMessageKey());
      if (event.getValues() == null){
         values.add(ImmutableList.of());
      }
      else{
         values.add(event.getNonNullValues());
      }
      values.add(event.getSubjectAddress());
      
      session.execute(stmt.bind(values.toArray()));

   }finally{
      if (metricsTimer != null) {
         metricsTimer.stop();
      }
   }
}
 
Example 20
Source File: MetricsUtil.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Stops the Metric Timer context.
 * <p>
 * If the given context was null, it will silently be ignored.
 * </p>
 *
 * @param context timing context to stop, if not null.
 */
public static void stopTimer(Context context) {
    if (context != null) {
        context.stop();
    }
}