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