View Javadoc

1   package com.atlassian.cache.memory;
2   
3   import java.util.SortedMap;
4   
5   import com.atlassian.cache.CacheStatisticsKey;
6   import com.atlassian.util.concurrent.Supplier;
7   
8   import com.google.common.cache.Cache;
9   import com.google.common.cache.LoadingCache;
10  import com.google.common.collect.ImmutableSortedMap;
11  
12  import static com.atlassian.cache.CacheStatisticsKey.EVICTION_COUNT;
13  import static com.atlassian.cache.CacheStatisticsKey.HIT_COUNT;
14  import static com.atlassian.cache.CacheStatisticsKey.MISS_COUNT;
15  import static com.atlassian.cache.CacheStatisticsKey.SIZE;
16  import static com.atlassian.cache.CacheStatisticsKey.TOTAL_MISS_TIME;
17  
18  /**
19   * @since v2.4.0
20   */
21  public class DelegatingCacheStatistics
22  {
23      public static SortedMap<CacheStatisticsKey,Supplier<Long>> toStatistics(Cache<?, ?> internalCache)
24      {
25          ImmutableSortedMap.Builder<CacheStatisticsKey, Supplier<Long>> map = ImmutableSortedMap.<CacheStatisticsKey, Supplier<Long>>orderedBy(CacheStatisticsKey.SORT_BY_LABEL)
26                  .put(SIZE, memoize(internalCache.size()))
27                  .put(HIT_COUNT, memoize(internalCache.stats().hitCount()))
28                  .put(MISS_COUNT, memoize(internalCache.stats().missCount()))
29                  .put(EVICTION_COUNT, memoize(internalCache.stats().evictionCount()));
30  
31          // don't bother reporting this statistic as "zero" for caches that
32          // can't even calculate it. Only LoadingCaches calculate it.
33          if (internalCache instanceof LoadingCache)
34          {
35              map.put(TOTAL_MISS_TIME, memoize(internalCache.stats().totalLoadTime()));
36          }
37  
38          return map.build();
39      }
40  
41      private static <V> Supplier<V> memoize(final V value)
42      {
43          return new ImmediateSupplier<V>(value);
44      }
45  
46      static class ImmediateSupplier<V> implements Supplier<V>
47      {
48          private final V value;
49  
50          ImmediateSupplier(final V value)
51          {
52              this.value = value;
53          }
54  
55          @Override
56          public V get()
57          {
58              return value;
59          }
60  
61          @Override
62          public String toString()
63          {
64              return "ImmediateSupplier[" + value + ']';
65          }
66      }
67  }