@Override
  public void report(SortedMap<String, Gauge> sortedMap, SortedMap<String, Counter> sortedMap1,
                     SortedMap<String, Histogram> sortedMap2, SortedMap<String, Meter> sortedMap3,
                     SortedMap<String, Timer> sortedMap4) {
    String json;
    try {
      json = jsonWriter.writeValueAsString(registry);
    } catch (JsonProcessingException e) {
      LOG.error("Unable to convert json to string ", e);
      return;
    }

    // Metrics are first dumped to a temp file which is then renamed to the destination
    Path tmpFile;
    try {
      tmpFile = Files.createTempFile(metricsDir, "hmsmetrics", "json", FILE_ATTRS);
    } catch (IOException e) {
      LOG.error("failed to create temp file for JSON metrics", e);
      return;
    } catch (SecurityException e) {
      // This shouldn't ever happen
      LOG.error("failed to create temp file for JSON metrics: no permissions", e);
      return;
    } catch (UnsupportedOperationException e) {
      // This shouldn't ever happen
      LOG.error("failed to create temp file for JSON metrics: operation not supported", e);
      return;
    }

    // Use try .. finally to cleanup temp file if something goes wrong
    try {
      // Write json to the temp file
      try (BufferedWriter bw = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8)) {
        bw.write(json);
      } catch (IOException e) {
        LOG.error("Unable to write to temp file {}", tmpFile, e);
        return;
      }

      // Atomically move temp file to the destination file
      try {
        Files.move(tmpFile, path, StandardCopyOption.ATOMIC_MOVE);
      } catch (Exception e) {
        LOG.error("Unable to rename temp file {} to {}", tmpFile, path);
        LOG.error("Exception during rename", e);
      }
    } finally {
      // If something happened and we were not able to rename the temp file, attempt to remove it
      if (tmpFile.toFile().exists()) {
        // Attempt to delete temp file, if this fails, not much can be done about it.
        try {
          Files.delete(tmpFile);
        } catch (Exception e) {
          LOG.error("failed to delete temporary metrics file " + tmpFile, e);
        }
      }
    }
  }
A metrics reporter for Metrics that dumps metrics periodically into
a file in JSON format.
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metrics/JsonReporter.java