View Javadoc

1   package com.atlassian.vcache.internal.core.metrics;
2   
3   import java.util.function.LongConsumer;
4   
5   import static java.util.Objects.requireNonNull;
6   
7   /**
8    * Utility timer for measuring the elapsed time using {@link System#nanoTime()}. Timing is started when the
9    * instance is created, and stopped when {@link #close()} is called.
10   *
11   * @since 1.0.0
12   */
13  public class ElapsedTimer implements AutoCloseable {
14      private final long startTime;
15      private final LongConsumer handler;
16  
17      /**
18       * Create an instance with a handler to be called with the total elapsed time.
19       *
20       * @param handler called when the timer has been closed.
21       */
22      public ElapsedTimer(LongConsumer handler) {
23          this.startTime = System.nanoTime();
24          this.handler = requireNonNull(handler);
25      }
26  
27      @Override
28      public void close() {
29          handler.accept(System.nanoTime() - startTime);
30      }
31  }