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 javax.annotation.Nullable;
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} are
035 *     incremented, and the total loading time, in nanoseconds, is added to {@code totalLoadTime}.
036 * <li>When an exception is thrown while loading an entry, {@code missCount} and {@code
037 *     loadExceptionCount} are incremented, and the total loading time, in nanoseconds, is added to
038 *     {@code totalLoadTime}.
039 * <li>Cache lookups that encounter a missing cache entry that is still loading will wait for
040 *     loading to complete (whether successful or not) and then increment {@code missCount}.
041 * </ul>
042 * <li>When an entry is evicted from the cache, {@code evictionCount} is incremented.
043 * <li>No stats are modified when a cache entry is invalidated or manually removed.
044 * <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of the
045 *     cache.
046 * </ul>
047 *
048 * <p>A lookup is specifically defined as an invocation of one of the methods
049 * {@link LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)},
050 * {@link Cache#get(Object, Callable)}, or {@link LoadingCache#getAll(Iterable)}.
051 *
052 * @author Charles Fry
053 * @since 10.0
054 */
055@GwtCompatible
056public final class CacheStats {
057  private final long hitCount;
058  private final long missCount;
059  private final long loadSuccessCount;
060  private final long loadExceptionCount;
061  private final long totalLoadTime;
062  private final long evictionCount;
063
064  /**
065   * Constructs a new {@code CacheStats} instance.
066   *
067   * <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
068   * by end users and is too fine-grained for a builder.
069   */
070  public CacheStats(
071      long hitCount,
072      long missCount,
073      long loadSuccessCount,
074      long loadExceptionCount,
075      long totalLoadTime,
076      long evictionCount) {
077    checkArgument(hitCount >= 0);
078    checkArgument(missCount >= 0);
079    checkArgument(loadSuccessCount >= 0);
080    checkArgument(loadExceptionCount >= 0);
081    checkArgument(totalLoadTime >= 0);
082    checkArgument(evictionCount >= 0);
083
084    this.hitCount = hitCount;
085    this.missCount = missCount;
086    this.loadSuccessCount = loadSuccessCount;
087    this.loadExceptionCount = loadExceptionCount;
088    this.totalLoadTime = totalLoadTime;
089    this.evictionCount = evictionCount;
090  }
091
092  /**
093   * Returns the number of times {@link Cache} lookup methods have returned either a cached or
094   * uncached value. This is defined as {@code hitCount + missCount}.
095   */
096  public long requestCount() {
097    return hitCount + missCount;
098  }
099
100  /**
101   * Returns the number of times {@link Cache} lookup methods have returned a cached value.
102   */
103  public long hitCount() {
104    return hitCount;
105  }
106
107  /**
108   * Returns the ratio of cache requests which were hits. This is defined as
109   * {@code hitCount / requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that
110   * {@code hitRate + 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
129   * {@code missCount / requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that
130   * {@code hitRate + missRate =~ 1.0}. Cache misses include all requests which weren't cache hits,
131   * including requests which resulted in either successful or failed loading attempts, and requests
132   * which waited for other threads to finish loading. It is thus the case that
133   * {@code missCount &gt;= loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for
134   * the same key will result 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
154   * {@link #loadExceptionCount}). Multiple concurrent misses for the same key will result in a
155   * single load operation. This may be incremented not in conjunction with {@code missCount} if the
156   * load occurs as a result of a refresh or if the cache loader returned more items than was
157   * requested. {@code missCount} may also be incremented not in conjunction with this (nor
158   * {@link #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
167   * {@code missCount} is also incremented when cache loading completes successfully (see
168   * {@link #loadSuccessCount}). Multiple concurrent misses for the same key will result in a single
169   * load operation. This may be incremented not in conjunction with {@code missCount} if the load
170   * occurs as a result of a refresh or if the cache loader returned more items than was requested.
171   * {@code missCount} may also be incremented not in conjunction with this (nor
172   * {@link #loadSuccessCount}) 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
180   * {@code loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when
181   * {@code 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
199   * {@code totalLoadTime / (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
231   * {@code 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(@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
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}