MetricsMap implements Serializable { public T get(K key) { T metric = metrics.get(key); if (metric == null) { metric = factory.createInstance(key); metric = MoreObjects.firstNonNull(metrics.putIfAbsent(key, metric), metric); } return metric; } MetricsMap(Factory<K, T> factory); T get(K key); @Nullable T tryGet(K key); Iterable<Map.Entry<K, T>> entries(); Iterable<T> values(); @Override boolean equals(@Nullable Object object); @Override int hashCode();  }
@Test public void testCreateSeparateInstances() { AtomicLong foo = metricsMap.get("foo"); AtomicLong bar = metricsMap.get("bar"); assertThat(foo, not(sameInstance(bar))); }
@Test public void testReuseInstances() { AtomicLong foo1 = metricsMap.get("foo"); AtomicLong foo2 = metricsMap.get("foo"); assertThat(foo1, sameInstance(foo2)); }
@Test public void testGet() { assertThat(metricsMap.tryGet("foo"), nullValue(AtomicLong.class)); AtomicLong foo = metricsMap.get("foo"); assertThat(metricsMap.tryGet("foo"), sameInstance(foo)); }