public static <T extends Metric> T safelyRegister(MetricRegistry metricRegistry, String name, T metric) {
        try {
            return metricRegistry.register(name, metric);
        } catch (IllegalArgumentException ignored) {
            // safely ignore already existing metric, and simply return the one registered previously.
            // note that we do not guard against differing metric types here, we consider that a programming error for now.

            //noinspection unchecked
            return (T) metricRegistry.getMetrics().get(name);
        }
    }
@Test
    public void safelyRegister() {

        final MetricRegistry metricRegistry = new MetricRegistry();

        final Gauge<Long> longGauge = new Gauge<>() {
            @Override
            public Long getValue() {
                return 0L;
            }
        };
        final Gauge<Long> newGauge = MetricUtils.safelyRegister(metricRegistry, "somename", longGauge);

        assertSame("metric objects are identical", longGauge, newGauge);

        try {
            MetricUtils.safelyRegister(metricRegistry, "somename", longGauge);
        } catch (Exception e) {
            fail("Should not have thrown: " + e.getMessage());
        }

        assertThatExceptionOfType(ClassCastException.class)
                .describedAs("Registering a metric with a different metric type fails on using it")
                .isThrownBy(() -> {
                    // assignment has to be done to raise the exception
                    Counter c = MetricUtils.safelyRegister(metricRegistry, "somename", new Counter());
                });
    }