aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/application/MetricImpl.java
blob: 0b73ead5e400b7316b51b0a1bcd4dd695618f2bd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.yahoo.jdisc.Metric;

import java.util.Map;

/**
 * @author Simon Thoresen Hult
 */
class MetricImpl implements Metric {

    private final LocalConsumer consumer;

    @Inject
    public MetricImpl(Provider<MetricConsumer> provider) {
        consumer = new LocalConsumer(provider);
    }

    @Override
    public void set(String key, Number val, Context ctx) {
        MetricConsumer consumer = currentConsumer();
        if (consumer != null) {
            consumer.set(key, val, ctx);
        }
    }

    @Override
    public void add(String key, Number val, Context ctx) {
        MetricConsumer consumer = currentConsumer();
        if (consumer != null) {
            consumer.add(key, val, ctx);
        }
    }

    @Override
    public Context createContext(Map<String, ?> keys) {
        MetricConsumer consumer = currentConsumer();
        if (consumer == null) {
            return null;
        }
        return consumer.createContext(keys);
    }

    private MetricConsumer currentConsumer() {
        return Thread.currentThread() instanceof ContainerThread thread ? thread.consumer() : consumer.get();
    }

    private static class LocalConsumer extends ThreadLocal<MetricConsumer> {

        final Provider<MetricConsumer> factory;

        LocalConsumer(Provider<MetricConsumer> factory) {
            this.factory = factory;
        }

        @Override
        protected MetricConsumer initialValue() {
            return factory.get();
        }
    }
}