### Question:
MetricRegistry { public Counter counter(final String id) { return counter(id, DEFAULT_MAX_CARDINALITY); } MetricRegistry(); Counter counter(final String id); Counter counter(final String id, final int maxCardinality); Gauge gauge(final String id); Gauge gauge(final String id, final int maxCardinality); GaugeDouble gaugeDouble(final String id); GaugeDouble gaugeDouble(final String id, final int maxCardinality); Timer timer(final String id); Timer timer(final String id, final int maxCardinality); T custom(final String id, final Class<T> klass); T custom(final String id, final Class<T> klass, final int maxCardinality); void addReporter(final Reporter reporter);  }### Answer:
@Test public void testReturnSameInstance() { MetricRegistry metricRegistry = new MetricRegistry(); Counter c = metricRegistry.counter("test"); assertEquals(c, metricRegistry.counter("test")); }
@Test public void testAlreadyDefinedSynchronized() throws InterruptedException { MetricRegistry metricRegistry = new MetricRegistry(); final Map<String, Metric> measurements = Deencapsulation .getField(metricRegistry, "measurements"); final AtomicBoolean success = new AtomicBoolean(false); final AtomicBoolean completed = new AtomicBoolean(false); synchronized (measurements) { Thread t = new Thread(() -> { try { metricRegistry.counter("test"); success.set(true); } catch (IllegalStateException e) { fail("No exception is thrown"); } finally { synchronized (completed) { completed.set(true); completed.notify(); } } }); t.start(); while (t.getState() != Thread.State.BLOCKED) { Thread.sleep(10); } measurements.put("test", new Counter(metricRegistry, "test", Metric.DEFAULT_MAX_CARDINALITY)); } synchronized (completed) { if (!completed.get()) { completed.wait(10_000); } } if (!completed.get()) { fail("Test thread did not complete!"); } if (!success.get()) { fail("Test thread succeeded in creating instance"); } }
@Test public void testAlreadyDefinedSynchronizedWrongType() throws InterruptedException { MetricRegistry metricRegistry = new MetricRegistry(); final Map<String, Metric> measurements = Deencapsulation .getField(metricRegistry, "measurements"); final AtomicBoolean success = new AtomicBoolean(false); final AtomicBoolean completed = new AtomicBoolean(false); synchronized (measurements) { Thread t = new Thread(() -> { try { metricRegistry.counter("test"); fail("No exception is thrown"); } catch (IllegalStateException e) { success.set(true); } finally { synchronized (completed) { completed.set(true); completed.notify(); } } }); t.start(); while (t.getState() != Thread.State.BLOCKED) { Thread.sleep(10); } measurements.put("test", new TestKlass("test")); } synchronized (completed) { if (!completed.get()) { completed.wait(10_000); } } if (!completed.get()) { fail("Test thread did not complete!"); } if (!success.get()) { fail("Test thread succeeded in creating instance"); } }