View Javadoc

1   package com.atlassian.vcache.internal.core.metrics;
2   
3   import javax.annotation.concurrent.NotThreadSafe;
4   import java.util.Optional;
5   import java.util.function.Consumer;
6   import java.util.function.Supplier;
7   
8   import static java.util.Objects.requireNonNull;
9   
10  /**
11   * Wrapper for a supplier used to create missing values. Calls the supplied handler with
12   * the elapsed time taken in nanoseconds, and {@link Optional#empty()} means it was was not called.
13   *
14   * @param <V> the value type
15   * @since 1.0.0
16   */
17  @NotThreadSafe
18  public class TimedSupplier<V> implements Supplier<V>, AutoCloseable {
19      private final Supplier<? extends V> delegate;
20      private final Consumer<Optional<Long>> handler;
21  
22      private Optional<Long> elapsedDuration = Optional.empty();
23  
24      public TimedSupplier(Supplier<V> delegate, Consumer<Optional<Long>> handler) {
25          this.delegate = requireNonNull(delegate);
26          this.handler = requireNonNull(handler);
27      }
28  
29      @Override
30      public V get() {
31          try (ElapsedTimer ignored = new ElapsedTimer(t -> elapsedDuration = Optional.of(t))) {
32              return delegate.get();
33          }
34      }
35  
36      @Override
37      public void close() {
38          handler.accept(elapsedDuration);
39      }
40  
41      public boolean wasInvoked() {
42          return elapsedDuration.isPresent();
43      }
44  }