aboutsummaryrefslogtreecommitdiffstats
path: root/container-disc/src/main/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumer.java
blob: 18aea820a1e1b4997238856c5dce6820648d5bcb (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;

import com.yahoo.container.jdisc.MetricConsumerFactory;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;

import java.util.Map;

/**
 * If more than one {@link MetricConsumerFactory} is registered in a container, calls to <code>Metric</code> need to be
 * forwarded to all the underlying <code>MetricConsumers</code>. That is the responsibility of this class.
 * Instances of this class is created by the {@link MetricConsumerProvider} in those cases.
 *
 * @author Simon Thoresen Hult
 */
public final class ForwardingMetricConsumer implements MetricConsumer {

    private final MetricConsumer[] consumers;

    public ForwardingMetricConsumer(MetricConsumer[] consumers) {
        this.consumers = consumers;
    }

    @Override
    public void set(String key, Number val, Metric.Context ctx) {
        ForwardingContext fwd = (ForwardingContext)ctx;
        for (int i = 0; i < consumers.length; ++i) {
            consumers[i].set(key, val, fwd != null ? fwd.contexts[i] : null);
        }
    }

    @Override
    public void add(String key, Number val, Metric.Context ctx) {
        ForwardingContext fwd = (ForwardingContext)ctx;
        for (int i = 0; i < consumers.length; ++i) {
            consumers[i].add(key, val, fwd != null ? fwd.contexts[i] : null);
        }
    }

    @Override
    public Metric.Context createContext(Map<String, ?> properties) {
        Metric.Context[] contexts = new Metric.Context[consumers.length];
        for (int i = 0; i < consumers.length; ++i) {
            contexts[i] = consumers[i].createContext(properties);
        }
        return new ForwardingContext(contexts);
    }

    private static class ForwardingContext implements Metric.Context {

        final Metric.Context[] contexts;

        ForwardingContext(Metric.Context[] contexts) {
            this.contexts = contexts;
        }
    }

}