Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleMetricsCollectingService
package org.folio.oaipmh.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Component
@EnableScheduling
public class MetricsCollectingService {

  protected final Logger logger = LogManager.getLogger(getClass());
  private static volatile int counter = 0;
  private static volatile int total = 0;

  private final List<MetricHit> hits = Collections.synchronizedList(new ArrayList<>());

  @Scheduled(fixedDelay = 60000, initialDelay = 60000)
  private void scheduledMetricsCollectionTask() {
    synchronized (hits) {
      if (!hits.isEmpty()) {
        Map<MetricOperation, Double> averages = hits.stream().collect(Collectors.groupingBy(MetricHit::getOperation, Collectors.averagingDouble(value -> (double) value.getDuration())));
        averages.forEach((operation, average) -> logger.info("Operation: {}  ---> Avg. {}", operation.name(), average));
      }
    }
  }

  public <T, R> MetricHit createMetricsHit(Function<T, R> function, T argument) {
    var startTimeInMs = System.currentTimeMillis();
    function.apply(argument);
    var stopTimeInMs = System.currentTimeMillis();
    var hit = MetricHit.builder()
      .operation(MetricOperation.FUNCTION)
      .duration(stopTimeInMs - startTimeInMs).build();
    synchronized (hits) {
      hits.add(hit);
    }
    return hit;
  }

  public  <T> MetricHit createMetricsHit(Predicate<T> predicate, T argument) {
    var startTimeInMs = System.currentTimeMillis();
    predicate.test(argument);
    var stopTimeInMs = System.currentTimeMillis();
    var hit = MetricHit.builder()
      .operation(MetricOperation.PREDICATE)
      .duration(stopTimeInMs - startTimeInMs).build();
    synchronized (hits) {
      hits.add(hit);
    }
    return hit;
  }
}

...