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