001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.cache;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.math.LongMath.saturatedAdd;
019import static com.google.common.math.LongMath.saturatedSubtract;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.base.MoreObjects;
023import com.google.common.base.Objects;
024import java.util.concurrent.Callable;
025import javax.annotation.CheckForNull;
026
027/**
028 * Statistics about the performance of a {@link Cache}. Instances of this class are immutable.
029 *
030 * <p>Cache statistics are incremented according to the following rules:
031 *
032 * <ul>
033 *   <li>When a cache lookup encounters an existing cache entry {@code hitCount} is incremented.
034 *   <li>When a cache lookup first encounters a missing cache entry, a new entry is loaded.
035 *       <ul>
036 *         <li>After successfully loading an entry {@code missCount} and {@code loadSuccessCount}
037 *             are incremented, and the total loading time, in nanoseconds, is added to {@code
038 *             totalLoadTime}.
039 *         <li>When an exception is thrown while loading an entry, {@code missCount} and {@code
040 *             loadExceptionCount} are incremented, and the total loading time, in nanoseconds, is
041 *             added to {@code totalLoadTime}.
042 *         <li>Cache lookups that encounter a missing cache entry that is still loading will wait
043 *             for loading to complete (whether successful or not) and then increment {@code
044 *             missCount}.
045 *       </ul>
046 *   <li>When an entry is evicted from the cache, {@code evictionCount} is incremented.
047 *   <li>No stats are modified when a cache entry is invalidated or manually removed.
048 *   <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of
049 *       the cache.
050 * </ul>
051 *
052 * <p>A lookup is specifically defined as an invocation of one of the methods {@link
053 * LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)}, {@link Cache#get(Object,
054 * Callable)}, or {@link LoadingCache#getAll(Iterable)}.
055 *
056 * @author Charles Fry
057 * @since 10.0
058 */
059@GwtCompatible
060@ElementTypesAreNonnullByDefault
061public final class CacheStats {
062  private final long hitCount;
063  private final long missCount;
064  private final long loadSuccessCount;
065  private final long loadExceptionCount;
066
067  @SuppressWarnings("GoodTime") // should be a java.time.Duration
068  private final long totalLoadTime;
069
070  private final long evictionCount;
071
072  /**
073   * Constructs a new {@code CacheStats} instance.
074   *
075   * <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
076   * by end users and is too fine-grained for a builder.
077   */
078  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
079  public CacheStats(
080      long hitCount,
081      long missCount,
082      long loadSuccessCount,
083      long loadExceptionCount,
084      long totalLoadTime,
085      long evictionCount) {
086    checkArgument(hitCount >= 0);
087    checkArgument(missCount >= 0);
088    checkArgument(loadSuccessCount >= 0);
089    checkArgument(loadExceptionCount >= 0);
090    checkArgument(totalLoadTime >= 0);
091    checkArgument(evictionCount >= 0);
092
093    this.hitCount = hitCount;
094    this.missCount = missCount;
095    this.loadSuccessCount = loadSuccessCount;
096    this.loadExceptionCount = loadExceptionCount;
097    this.totalLoadTime = totalLoadTime;
098    this.evictionCount = evictionCount;
099  }
100
101  /**
102   * Returns the number of times {@link Cache} lookup methods have returned either a cached or
103   * uncached value. This is defined as {@code hitCount + missCount}.
104   *
105   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
106   * guaranteed not to throw an exception). If you require specific handling, we recommend
107   * implementing your own stats collector.
108   */
109  public long requestCount() {
110    return saturatedAdd(hitCount, missCount);
111  }
112
113  /** Returns the number of times {@link Cache} lookup methods have returned a cached value. */
114  public long hitCount() {
115    return hitCount;
116  }
117
118  /**
119   * Returns the ratio of cache requests which were hits. This is defined as {@code hitCount /
120   * requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that {@code hitRate +
121   * missRate =~ 1.0}.
122   */
123  public double hitRate() {
124    long requestCount = requestCount();
125    return (requestCount == 0) ? 1.0 : (double) hitCount / requestCount;
126  }
127
128  /**
129   * Returns the number of times {@link Cache} lookup methods have returned an uncached (newly
130   * loaded) value, or null. Multiple concurrent calls to {@link Cache} lookup methods on an absent
131   * value can result in multiple misses, all returning the results of a single cache load
132   * operation.
133   */
134  public long missCount() {
135    return missCount;
136  }
137
138  /**
139   * Returns the ratio of cache requests which were misses. This is defined as {@code missCount /
140   * requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that {@code hitRate +
141   * missRate =~ 1.0}. Cache misses include all requests which weren't cache hits, including
142   * requests which resulted in either successful or failed loading attempts, and requests which
143   * waited for other threads to finish loading. It is thus the case that {@code missCount &gt;=
144   * loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for the same key will result
145   * in a single load operation.
146   */
147  public double missRate() {
148    long requestCount = requestCount();
149    return (requestCount == 0) ? 0.0 : (double) missCount / requestCount;
150  }
151
152  /**
153   * Returns the total number of times that {@link Cache} lookup methods attempted to load new
154   * values. This includes both successful load operations, as well as those that threw exceptions.
155   * This is defined as {@code loadSuccessCount + loadExceptionCount}.
156   *
157   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
158   * guaranteed not to throw an exception). If you require specific handling, we recommend
159   * implementing your own stats collector.
160   */
161  public long loadCount() {
162    return saturatedAdd(loadSuccessCount, loadExceptionCount);
163  }
164
165  /**
166   * Returns the number of times {@link Cache} lookup methods have successfully loaded a new value.
167   * This is usually incremented in conjunction with {@link #missCount}, though {@code missCount} is
168   * also incremented when an exception is encountered during cache loading (see {@link
169   * #loadExceptionCount}). Multiple concurrent misses for the same key will result in a single load
170   * operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
171   * as a result of a refresh or if the cache loader returned more items than was requested. {@code
172   * missCount} may also be incremented not in conjunction with this (nor {@link
173   * #loadExceptionCount}) on calls to {@code getIfPresent}.
174   */
175  public long loadSuccessCount() {
176    return loadSuccessCount;
177  }
178
179  /**
180   * Returns the number of times {@link Cache} lookup methods threw an exception while loading a new
181   * value. This is usually incremented in conjunction with {@code missCount}, though {@code
182   * missCount} is also incremented when cache loading completes successfully (see {@link
183   * #loadSuccessCount}). Multiple concurrent misses for the same key will result in a single load
184   * operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
185   * as a result of a refresh or if the cache loader returned more items than was requested. {@code
186   * missCount} may also be incremented not in conjunction with this (nor {@link #loadSuccessCount})
187   * on calls to {@code getIfPresent}.
188   */
189  public long loadExceptionCount() {
190    return loadExceptionCount;
191  }
192
193  /**
194   * Returns the ratio of cache loading attempts which threw exceptions. This is defined as {@code
195   * loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when {@code
196   * loadSuccessCount + loadExceptionCount == 0}.
197   *
198   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
199   * guaranteed not to throw an exception). If you require specific handling, we recommend
200   * implementing your own stats collector.
201   */
202  public double loadExceptionRate() {
203    long totalLoadCount = saturatedAdd(loadSuccessCount, loadExceptionCount);
204    return (totalLoadCount == 0) ? 0.0 : (double) loadExceptionCount / totalLoadCount;
205  }
206
207  /**
208   * Returns the total number of nanoseconds the cache has spent loading new values. This can be
209   * used to calculate the miss penalty. This value is increased every time {@code loadSuccessCount}
210   * or {@code loadExceptionCount} is incremented.
211   */
212  @SuppressWarnings("GoodTime") // should return a java.time.Duration
213  public long totalLoadTime() {
214    return totalLoadTime;
215  }
216
217  /**
218   * Returns the average time spent loading new values. This is defined as {@code totalLoadTime /
219   * (loadSuccessCount + loadExceptionCount)}.
220   *
221   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
222   * guaranteed not to throw an exception). If you require specific handling, we recommend
223   * implementing your own stats collector.
224   */
225  public double averageLoadPenalty() {
226    long totalLoadCount = saturatedAdd(loadSuccessCount, loadExceptionCount);
227    return (totalLoadCount == 0) ? 0.0 : (double) totalLoadTime / totalLoadCount;
228  }
229
230  /**
231   * Returns the number of times an entry has been evicted. This count does not include manual
232   * {@linkplain Cache#invalidate invalidations}.
233   */
234  public long evictionCount() {
235    return evictionCount;
236  }
237
238  /**
239   * Returns a new {@code CacheStats} representing the difference between this {@code CacheStats}
240   * and {@code other}. Negative values, which aren't supported by {@code CacheStats} will be
241   * rounded up to zero.
242   */
243  public CacheStats minus(CacheStats other) {
244    return new CacheStats(
245        Math.max(0, saturatedSubtract(hitCount, other.hitCount)),
246        Math.max(0, saturatedSubtract(missCount, other.missCount)),
247        Math.max(0, saturatedSubtract(loadSuccessCount, other.loadSuccessCount)),
248        Math.max(0, saturatedSubtract(loadExceptionCount, other.loadExceptionCount)),
249        Math.max(0, saturatedSubtract(totalLoadTime, other.totalLoadTime)),
250        Math.max(0, saturatedSubtract(evictionCount, other.evictionCount)));
251  }
252
253  /**
254   * Returns a new {@code CacheStats} representing the sum of this {@code CacheStats} and {@code
255   * other}.
256   *
257   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
258   * guaranteed not to throw an exception). If you require specific handling, we recommend
259   * implementing your own stats collector.
260   *
261   * @since 11.0
262   */
263  public CacheStats plus(CacheStats other) {
264    return new CacheStats(
265        saturatedAdd(hitCount, other.hitCount),
266        saturatedAdd(missCount, other.missCount),
267        saturatedAdd(loadSuccessCount, other.loadSuccessCount),
268        saturatedAdd(loadExceptionCount, other.loadExceptionCount),
269        saturatedAdd(totalLoadTime, other.totalLoadTime),
270        saturatedAdd(evictionCount, other.evictionCount));
271  }
272
273  @Override
274  public int hashCode() {
275    return Objects.hashCode(
276        hitCount, missCount, loadSuccessCount, loadExceptionCount, totalLoadTime, evictionCount);
277  }
278
279  @Override
280  public boolean equals(@CheckForNull Object object) {
281    if (object instanceof CacheStats) {
282      CacheStats other = (CacheStats) object;
283      return hitCount == other.hitCount
284          && missCount == other.missCount
285          && loadSuccessCount == other.loadSuccessCount
286          && loadExceptionCount == other.loadExceptionCount
287          && totalLoadTime == other.totalLoadTime
288          && evictionCount == other.evictionCount;
289    }
290    return false;
291  }
292
293  @Override
294  public String toString() {
295    return MoreObjects.toStringHelper(this)
296        .add("hitCount", hitCount)
297        .add("missCount", missCount)
298        .add("loadSuccessCount", loadSuccessCount)
299        .add("loadExceptionCount", loadExceptionCount)
300        .add("totalLoadTime", totalLoadTime)
301        .add("evictionCount", evictionCount)
302        .toString();
303  }
304}