1 package com.atlassian.vcache.internal.core.metrics;
2
3 import java.util.Map;
4 import java.util.Optional;
5 import java.util.Set;
6 import java.util.function.BiConsumer;
7 import java.util.function.Function;
8
9 import static java.util.Objects.requireNonNull;
10
11
12
13
14
15
16
17
18
19
20 class TimedFactory<K, V> implements Function<Set<K>, Map<K, V>>, AutoCloseable {
21 private final Function<Set<K>, Map<K, V>> delegate;
22 private final BiConsumer<Optional<Long>, Long> handler;
23
24 private Optional<Long> elapsedDuration = Optional.empty();
25 private long numberOfKeys;
26
27 TimedFactory(Function<Set<K>, Map<K, V>> delegate, BiConsumer<Optional<Long>, Long> handler) {
28 this.delegate = requireNonNull(delegate);
29 this.handler = requireNonNull(handler);
30 }
31
32 @Override
33 public Map<K, V> apply(Set<K> keys) {
34 try (ElapsedTimer ignored = new ElapsedTimer(t -> {
35 elapsedDuration = Optional.of(t);
36 numberOfKeys = (long) keys.size();
37 })) {
38 return delegate.apply(keys);
39 }
40 }
41
42 @Override
43 public void close() {
44 handler.accept(elapsedDuration, numberOfKeys);
45 }
46
47 long getNumberOfKeys() {
48 return numberOfKeys;
49 }
50 }