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  private final long totalLoadTime;
064  private final long evictionCount;
065
066  /**
067   * Constructs a new {@code CacheStats} instance.
068   *
069   * <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
070   * by end users and is too fine-grained for a builder.
071   */
072  public CacheStats(
073      long hitCount,
074      long missCount,
075      long loadSuccessCount,
076      long loadExceptionCount,
077      long totalLoadTime,
078      long evictionCount) {
079    checkArgument(hitCount >= 0);
080    checkArgument(missCount >= 0);
081    checkArgument(loadSuccessCount >= 0);
082    checkArgument(loadExceptionCount >= 0);
083    checkArgument(totalLoadTime >= 0);
084    checkArgument(evictionCount >= 0);
085
086    this.hitCount = hitCount;
087    this.missCount = missCount;
088    this.loadSuccessCount = loadSuccessCount;
089    this.loadExceptionCount = loadExceptionCount;
090    this.totalLoadTime = totalLoadTime;
091    this.evictionCount = evictionCount;
092  }
093
094  /**
095   * Returns the number of times {@link Cache} lookup methods have returned either a cached or
096   * uncached value. This is defined as {@code hitCount + missCount}.
097   */
098  public long requestCount() {
099    return hitCount + missCount;
100  }
101
102  /** Returns the number of times {@link Cache} lookup methods have returned a cached value. */
103  public long hitCount() {
104    return hitCount;
105  }
106
107  /**
108   * Returns the ratio of cache requests which were hits. This is defined as {@code hitCount /
109   * requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that {@code hitRate +
110   * 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 {@code missCount /
129   * requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that {@code hitRate +
130   * missRate =~ 1.0}. Cache misses include all requests which weren't cache hits, including
131   * requests which resulted in either successful or failed loading attempts, and requests which
132   * waited for other threads to finish loading. It is thus the case that {@code missCount &gt;=
133   * loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for the same key will result
134   * 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 {@link
154   * #loadExceptionCount}). Multiple concurrent misses for the same key will result in a single load
155   * operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
156   * as a result of a refresh or if the cache loader returned more items than was requested. {@code
157   * missCount} may also be incremented not in conjunction with this (nor {@link
158   * #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 {@code
167   * missCount} is also incremented when cache loading completes successfully (see {@link
168   * #loadSuccessCount}). 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 #loadSuccessCount})
172   * 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 {@code
180   * loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when {@code
181   * 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 {@code totalLoadTime /
199   * (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 {@code
231   * 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(@NullableDecl 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}