View Javadoc
1   /*
2    * Copyright (C) 2011 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.cache;
16  
17  import static com.google.common.base.Preconditions.checkArgument;
18  
19  import com.google.common.annotations.GwtCompatible;
20  import com.google.common.base.MoreObjects;
21  import com.google.common.base.Objects;
22  import java.util.concurrent.Callable;
23  import javax.annotation.Nullable;
24  
25  /**
26   * Statistics about the performance of a {@link Cache}. Instances of this class are immutable.
27   *
28   * <p>Cache statistics are incremented according to the following rules:
29   *
30   * <ul>
31   * <li>When a cache lookup encounters an existing cache entry {@code hitCount} is incremented.
32   * <li>When a cache lookup first encounters a missing cache entry, a new entry is loaded.
33   * <ul>
34   * <li>After successfully loading an entry {@code missCount} and {@code loadSuccessCount} are
35   *     incremented, and the total loading time, in nanoseconds, is added to {@code totalLoadTime}.
36   * <li>When an exception is thrown while loading an entry, {@code missCount} and {@code
37   *     loadExceptionCount} are incremented, and the total loading time, in nanoseconds, is added to
38   *     {@code totalLoadTime}.
39   * <li>Cache lookups that encounter a missing cache entry that is still loading will wait for
40   *     loading to complete (whether successful or not) and then increment {@code missCount}.
41   * </ul>
42   * <li>When an entry is evicted from the cache, {@code evictionCount} is incremented.
43   * <li>No stats are modified when a cache entry is invalidated or manually removed.
44   * <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of the
45   *     cache.
46   * </ul>
47   *
48   * <p>A lookup is specifically defined as an invocation of one of the methods
49   * {@link LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)},
50   * {@link Cache#get(Object, Callable)}, or {@link LoadingCache#getAll(Iterable)}.
51   *
52   * @author Charles Fry
53   * @since 10.0
54   */
55  @GwtCompatible
56  public final class CacheStats {
57    private final long hitCount;
58    private final long missCount;
59    private final long loadSuccessCount;
60    private final long loadExceptionCount;
61    private final long totalLoadTime;
62    private final long evictionCount;
63  
64    /**
65     * Constructs a new {@code CacheStats} instance.
66     *
67     * <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
68     * by end users and is too fine-grained for a builder.
69     */
70    public CacheStats(
71        long hitCount,
72        long missCount,
73        long loadSuccessCount,
74        long loadExceptionCount,
75        long totalLoadTime,
76        long evictionCount) {
77      checkArgument(hitCount >= 0);
78      checkArgument(missCount >= 0);
79      checkArgument(loadSuccessCount >= 0);
80      checkArgument(loadExceptionCount >= 0);
81      checkArgument(totalLoadTime >= 0);
82      checkArgument(evictionCount >= 0);
83  
84      this.hitCount = hitCount;
85      this.missCount = missCount;
86      this.loadSuccessCount = loadSuccessCount;
87      this.loadExceptionCount = loadExceptionCount;
88      this.totalLoadTime = totalLoadTime;
89      this.evictionCount = evictionCount;
90    }
91  
92    /**
93     * Returns the number of times {@link Cache} lookup methods have returned either a cached or
94     * uncached value. This is defined as {@code hitCount + missCount}.
95     */
96    public long requestCount() {
97      return hitCount + missCount;
98    }
99  
100   /**
101    * Returns the number of times {@link Cache} lookup methods have returned a cached value.
102    */
103   public long hitCount() {
104     return hitCount;
105   }
106 
107   /**
108    * Returns the ratio of cache requests which were hits. This is defined as
109    * {@code hitCount / requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that
110    * {@code hitRate + missRate =~ 1.0}.
111    */
112   public double hitRate() {
113     long requestCount = requestCount();
114     return (requestCount == 0) ? 1.0 : (double) hitCount / requestCount;
115   }
116 
117   /**
118    * Returns the number of times {@link Cache} lookup methods have returned an uncached (newly
119    * loaded) value, or null. Multiple concurrent calls to {@link Cache} lookup methods on an absent
120    * value can result in multiple misses, all returning the results of a single cache load
121    * operation.
122    */
123   public long missCount() {
124     return missCount;
125   }
126 
127   /**
128    * Returns the ratio of cache requests which were misses. This is defined as
129    * {@code missCount / requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that
130    * {@code hitRate + missRate =~ 1.0}. Cache misses include all requests which weren't cache hits,
131    * including requests which resulted in either successful or failed loading attempts, and requests
132    * which waited for other threads to finish loading. It is thus the case that
133    * {@code missCount &gt;= loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for
134    * the same key will result in a single load operation.
135    */
136   public double missRate() {
137     long requestCount = requestCount();
138     return (requestCount == 0) ? 0.0 : (double) missCount / requestCount;
139   }
140 
141   /**
142    * Returns the total number of times that {@link Cache} lookup methods attempted to load new
143    * values. This includes both successful load operations, as well as those that threw exceptions.
144    * This is defined as {@code loadSuccessCount + loadExceptionCount}.
145    */
146   public long loadCount() {
147     return loadSuccessCount + loadExceptionCount;
148   }
149 
150   /**
151    * Returns the number of times {@link Cache} lookup methods have successfully loaded a new value.
152    * This is usually incremented in conjunction with {@link #missCount}, though {@code missCount} is
153    * also incremented when an exception is encountered during cache loading (see
154    * {@link #loadExceptionCount}). Multiple concurrent misses for the same key will result in a
155    * single load operation. This may be incremented not in conjunction with {@code missCount} if the
156    * load occurs as a result of a refresh or if the cache loader returned more items than was
157    * requested. {@code missCount} may also be incremented not in conjunction with this (nor
158    * {@link #loadExceptionCount}) on calls to {@code getIfPresent}.
159    */
160   public long loadSuccessCount() {
161     return loadSuccessCount;
162   }
163 
164   /**
165    * Returns the number of times {@link Cache} lookup methods threw an exception while loading a new
166    * value. This is usually incremented in conjunction with {@code missCount}, though
167    * {@code missCount} is also incremented when cache loading completes successfully (see
168    * {@link #loadSuccessCount}). Multiple concurrent misses for the same key will result in a single
169    * load operation. This may be incremented not in conjunction with {@code missCount} if the load
170    * occurs as a result of a refresh or if the cache loader returned more items than was requested.
171    * {@code missCount} may also be incremented not in conjunction with this (nor
172    * {@link #loadSuccessCount}) on calls to {@code getIfPresent}.
173    */
174   public long loadExceptionCount() {
175     return loadExceptionCount;
176   }
177 
178   /**
179    * Returns the ratio of cache loading attempts which threw exceptions. This is defined as
180    * {@code loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when
181    * {@code loadSuccessCount + loadExceptionCount == 0}.
182    */
183   public double loadExceptionRate() {
184     long totalLoadCount = loadSuccessCount + loadExceptionCount;
185     return (totalLoadCount == 0) ? 0.0 : (double) loadExceptionCount / totalLoadCount;
186   }
187 
188   /**
189    * Returns the total number of nanoseconds the cache has spent loading new values. This can be
190    * used to calculate the miss penalty. This value is increased every time {@code loadSuccessCount}
191    * or {@code loadExceptionCount} is incremented.
192    */
193   public long totalLoadTime() {
194     return totalLoadTime;
195   }
196 
197   /**
198    * Returns the average time spent loading new values. This is defined as
199    * {@code totalLoadTime / (loadSuccessCount + loadExceptionCount)}.
200    */
201   public double averageLoadPenalty() {
202     long totalLoadCount = loadSuccessCount + loadExceptionCount;
203     return (totalLoadCount == 0) ? 0.0 : (double) totalLoadTime / totalLoadCount;
204   }
205 
206   /**
207    * Returns the number of times an entry has been evicted. This count does not include manual
208    * {@linkplain Cache#invalidate invalidations}.
209    */
210   public long evictionCount() {
211     return evictionCount;
212   }
213 
214   /**
215    * Returns a new {@code CacheStats} representing the difference between this {@code CacheStats}
216    * and {@code other}. Negative values, which aren't supported by {@code CacheStats} will be
217    * rounded up to zero.
218    */
219   public CacheStats minus(CacheStats other) {
220     return new CacheStats(
221         Math.max(0, hitCount - other.hitCount),
222         Math.max(0, missCount - other.missCount),
223         Math.max(0, loadSuccessCount - other.loadSuccessCount),
224         Math.max(0, loadExceptionCount - other.loadExceptionCount),
225         Math.max(0, totalLoadTime - other.totalLoadTime),
226         Math.max(0, evictionCount - other.evictionCount));
227   }
228 
229   /**
230    * Returns a new {@code CacheStats} representing the sum of this {@code CacheStats} and
231    * {@code other}.
232    *
233    * @since 11.0
234    */
235   public CacheStats plus(CacheStats other) {
236     return new CacheStats(
237         hitCount + other.hitCount,
238         missCount + other.missCount,
239         loadSuccessCount + other.loadSuccessCount,
240         loadExceptionCount + other.loadExceptionCount,
241         totalLoadTime + other.totalLoadTime,
242         evictionCount + other.evictionCount);
243   }
244 
245   @Override
246   public int hashCode() {
247     return Objects.hashCode(
248         hitCount, missCount, loadSuccessCount, loadExceptionCount, totalLoadTime, evictionCount);
249   }
250 
251   @Override
252   public boolean equals(@Nullable Object object) {
253     if (object instanceof CacheStats) {
254       CacheStats other = (CacheStats) object;
255       return hitCount == other.hitCount
256           && missCount == other.missCount
257           && loadSuccessCount == other.loadSuccessCount
258           && loadExceptionCount == other.loadExceptionCount
259           && totalLoadTime == other.totalLoadTime
260           && evictionCount == other.evictionCount;
261     }
262     return false;
263   }
264 
265   @Override
266   public String toString() {
267     return MoreObjects.toStringHelper(this)
268         .add("hitCount", hitCount)
269         .add("missCount", missCount)
270         .add("loadSuccessCount", loadSuccessCount)
271         .add("loadExceptionCount", loadExceptionCount)
272         .add("totalLoadTime", totalLoadTime)
273         .add("evictionCount", evictionCount)
274         .toString();
275   }
276 }