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 org.checkerframework.checker.nullness.qual.Nullable;
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
060public final class CacheStats {
061  private final long hitCount;
062  private final long missCount;
063  private final long loadSuccessCount;
064  private final long loadExceptionCount;
065
066  @SuppressWarnings("GoodTime") // should be a java.time.Duration
067  private final long totalLoadTime;
068
069  private final long evictionCount;
070
071  /**
072   * Constructs a new {@code CacheStats} instance.
073   *
074   * <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
075   * by end users and is too fine-grained for a builder.
076   */
077  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
078  public CacheStats(
079      long hitCount,
080      long missCount,
081      long loadSuccessCount,
082      long loadExceptionCount,
083      long totalLoadTime,
084      long evictionCount) {
085    checkArgument(hitCount >= 0);
086    checkArgument(missCount >= 0);
087    checkArgument(loadSuccessCount >= 0);
088    checkArgument(loadExceptionCount >= 0);
089    checkArgument(totalLoadTime >= 0);
090    checkArgument(evictionCount >= 0);
091
092    this.hitCount = hitCount;
093    this.missCount = missCount;
094    this.loadSuccessCount = loadSuccessCount;
095    this.loadExceptionCount = loadExceptionCount;
096    this.totalLoadTime = totalLoadTime;
097    this.evictionCount = evictionCount;
098  }
099
100  /**
101   * Returns the number of times {@link Cache} lookup methods have returned either a cached or
102   * uncached value. This is defined as {@code hitCount + missCount}.
103   *
104   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
105   * guaranteed not to throw an exception). If you require specific handling, we recommend
106   * implementing your own stats collector.
107   */
108  public long requestCount() {
109    return saturatedAdd(hitCount, missCount);
110  }
111
112  /** Returns the number of times {@link Cache} lookup methods have returned a cached value. */
113  public long hitCount() {
114    return hitCount;
115  }
116
117  /**
118   * Returns the ratio of cache requests which were hits. This is defined as {@code hitCount /
119   * requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that {@code hitRate +
120   * missRate =~ 1.0}.
121   */
122  public double hitRate() {
123    long requestCount = requestCount();
124    return (requestCount == 0) ? 1.0 : (double) hitCount / requestCount;
125  }
126
127  /**
128   * Returns the number of times {@link Cache} lookup methods have returned an uncached (newly
129   * loaded) value, or null. Multiple concurrent calls to {@link Cache} lookup methods on an absent
130   * value can result in multiple misses, all returning the results of a single cache load
131   * operation.
132   */
133  public long missCount() {
134    return missCount;
135  }
136
137  /**
138   * Returns the ratio of cache requests which were misses. This is defined as {@code missCount /
139   * requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that {@code hitRate +
140   * missRate =~ 1.0}. Cache misses include all requests which weren't cache hits, including
141   * requests which resulted in either successful or failed loading attempts, and requests which
142   * waited for other threads to finish loading. It is thus the case that {@code missCount &gt;=
143   * loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for the same key will result
144   * in a single load operation.
145   */
146  public double missRate() {
147    long requestCount = requestCount();
148    return (requestCount == 0) ? 0.0 : (double) missCount / requestCount;
149  }
150
151  /**
152   * Returns the total number of times that {@link Cache} lookup methods attempted to load new
153   * values. This includes both successful load operations, as well as those that threw exceptions.
154   * This is defined as {@code loadSuccessCount + loadExceptionCount}.
155   *
156   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
157   * guaranteed not to throw an exception). If you require specific handling, we recommend
158   * implementing your own stats collector.
159   */
160  public long loadCount() {
161    return saturatedAdd(loadSuccessCount, loadExceptionCount);
162  }
163
164  /**
165   * Returns the number of times {@link Cache} lookup methods have successfully loaded a new value.
166   * This is usually incremented in conjunction with {@link #missCount}, though {@code missCount} is
167   * also incremented when an exception is encountered during cache loading (see {@link
168   * #loadExceptionCount}). Multiple concurrent misses for the same key will result in a single load
169   * operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
170   * as a result of a refresh or if the cache loader returned more items than was requested. {@code
171   * missCount} may also be incremented not in conjunction with this (nor {@link
172   * #loadExceptionCount}) on calls to {@code getIfPresent}.
173   */
174  public long loadSuccessCount() {
175    return loadSuccessCount;
176  }
177
178  /**
179   * Returns the number of times {@link Cache} lookup methods threw an exception while loading a new
180   * value. This is usually incremented in conjunction with {@code missCount}, though {@code
181   * missCount} is also incremented when cache loading completes successfully (see {@link
182   * #loadSuccessCount}). Multiple concurrent misses for the same key will result in a single load
183   * operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
184   * as a result of a refresh or if the cache loader returned more items than was requested. {@code
185   * missCount} may also be incremented not in conjunction with this (nor {@link #loadSuccessCount})
186   * on calls to {@code getIfPresent}.
187   */
188  public long loadExceptionCount() {
189    return loadExceptionCount;
190  }
191
192  /**
193   * Returns the ratio of cache loading attempts which threw exceptions. This is defined as {@code
194   * loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when {@code
195   * loadSuccessCount + loadExceptionCount == 0}.
196   *
197   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
198   * guaranteed not to throw an exception). If you require specific handling, we recommend
199   * implementing your own stats collector.
200   */
201  public double loadExceptionRate() {
202    long totalLoadCount = saturatedAdd(loadSuccessCount, loadExceptionCount);
203    return (totalLoadCount == 0) ? 0.0 : (double) loadExceptionCount / totalLoadCount;
204  }
205
206  /**
207   * Returns the total number of nanoseconds the cache has spent loading new values. This can be
208   * used to calculate the miss penalty. This value is increased every time {@code loadSuccessCount}
209   * or {@code loadExceptionCount} is incremented.
210   */
211  @SuppressWarnings("GoodTime") // should return a java.time.Duration
212  public long totalLoadTime() {
213    return totalLoadTime;
214  }
215
216  /**
217   * Returns the average time spent loading new values. This is defined as {@code totalLoadTime /
218   * (loadSuccessCount + loadExceptionCount)}.
219   *
220   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
221   * guaranteed not to throw an exception). If you require specific handling, we recommend
222   * implementing your own stats collector.
223   */
224  public double averageLoadPenalty() {
225    long totalLoadCount = saturatedAdd(loadSuccessCount, loadExceptionCount);
226    return (totalLoadCount == 0) ? 0.0 : (double) totalLoadTime / totalLoadCount;
227  }
228
229  /**
230   * Returns the number of times an entry has been evicted. This count does not include manual
231   * {@linkplain Cache#invalidate invalidations}.
232   */
233  public long evictionCount() {
234    return evictionCount;
235  }
236
237  /**
238   * Returns a new {@code CacheStats} representing the difference between this {@code CacheStats}
239   * and {@code other}. Negative values, which aren't supported by {@code CacheStats} will be
240   * rounded up to zero.
241   */
242  public CacheStats minus(CacheStats other) {
243    return new CacheStats(
244        Math.max(0, saturatedSubtract(hitCount, other.hitCount)),
245        Math.max(0, saturatedSubtract(missCount, other.missCount)),
246        Math.max(0, saturatedSubtract(loadSuccessCount, other.loadSuccessCount)),
247        Math.max(0, saturatedSubtract(loadExceptionCount, other.loadExceptionCount)),
248        Math.max(0, saturatedSubtract(totalLoadTime, other.totalLoadTime)),
249        Math.max(0, saturatedSubtract(evictionCount, other.evictionCount)));
250  }
251
252  /**
253   * Returns a new {@code CacheStats} representing the sum of this {@code CacheStats} and {@code
254   * other}.
255   *
256   * <p><b>Note:</b> the values of the metrics are undefined in case of overflow (though it is
257   * guaranteed not to throw an exception). If you require specific handling, we recommend
258   * implementing your own stats collector.
259   *
260   * @since 11.0
261   */
262  public CacheStats plus(CacheStats other) {
263    return new CacheStats(
264        saturatedAdd(hitCount, other.hitCount),
265        saturatedAdd(missCount, other.missCount),
266        saturatedAdd(loadSuccessCount, other.loadSuccessCount),
267        saturatedAdd(loadExceptionCount, other.loadExceptionCount),
268        saturatedAdd(totalLoadTime, other.totalLoadTime),
269        saturatedAdd(evictionCount, other.evictionCount));
270  }
271
272  @Override
273  public int hashCode() {
274    return Objects.hashCode(
275        hitCount, missCount, loadSuccessCount, loadExceptionCount, totalLoadTime, evictionCount);
276  }
277
278  @Override
279  public boolean equals(@Nullable Object object) {
280    if (object instanceof CacheStats) {
281      CacheStats other = (CacheStats) object;
282      return hitCount == other.hitCount
283          && missCount == other.missCount
284          && loadSuccessCount == other.loadSuccessCount
285          && loadExceptionCount == other.loadExceptionCount
286          && totalLoadTime == other.totalLoadTime
287          && evictionCount == other.evictionCount;
288    }
289    return false;
290  }
291
292  @Override
293  public String toString() {
294    return MoreObjects.toStringHelper(this)
295        .add("hitCount", hitCount)
296        .add("missCount", missCount)
297        .add("loadSuccessCount", loadSuccessCount)
298        .add("loadExceptionCount", loadExceptionCount)
299        .add("totalLoadTime", totalLoadTime)
300        .add("evictionCount", evictionCount)
301        .toString();
302  }
303}