001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.cache;
018
019import static com.google.common.base.Preconditions.checkArgument;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.base.MoreObjects;
023import com.google.common.base.Objects;
024
025import java.util.concurrent.Callable;
026
027import javax.annotation.Nullable;
028
029/**
030 * Statistics about the performance of a {@link Cache}. Instances of this class are immutable.
031 *
032 * <p>Cache statistics are incremented according to the following rules:
033 *
034 * <ul>
035 * <li>When a cache lookup encounters an existing cache entry {@code hitCount} is incremented.
036 * <li>When a cache lookup first encounters a missing cache entry, a new entry is loaded.
037 * <ul>
038 * <li>After successfully loading an entry {@code missCount} and {@code loadSuccessCount} are
039 *     incremented, and the total loading time, in nanoseconds, is added to
040 *     {@code totalLoadTime}.
041 * <li>When an exception is thrown while loading an entry, {@code missCount} and {@code
042 *     loadExceptionCount} are incremented, and the total loading time, in nanoseconds, is
043 *     added to {@code totalLoadTime}.
044 * <li>Cache lookups that encounter a missing cache entry that is still loading will wait
045 *     for loading to complete (whether successful or not) and then increment {@code missCount}.
046 * </ul>
047 * <li>When an entry is evicted from the cache, {@code evictionCount} is incremented.
048 * <li>No stats are modified when a cache entry is invalidated or manually removed.
049 * <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of
050 *     the cache.
051 * </ul>
052 * 
053 * <p>A lookup is specifically defined as an invocation of one of the methods 
054 * {@link LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)}, 
055 * {@link Cache#get(Object, Callable)}, or {@link LoadingCache#getAll(Iterable)}.
056 *
057 * @author Charles Fry
058 * @since 10.0
059 */
060@GwtCompatible
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  private final long totalLoadTime;
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  public CacheStats(long hitCount, long missCount, long loadSuccessCount,
076      long loadExceptionCount, long totalLoadTime, 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}.
110   * Note that {@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}.
130   * Note that {@code hitRate + missRate =~ 1.0}. Cache misses include all requests which
131   * weren't cache hits, including requests which resulted in either successful or failed loading
132   * attempts, and requests which waited for other threads to finish loading. It is thus the case
133   * that {@code missCount &gt;= loadSuccessCount + loadExceptionCount}. Multiple
134   * concurrent misses for 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
144   * exceptions. 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 always incremented in conjunction with {@link #missCount}, though {@code missCount}
153   * is 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.
156   */
157  public long loadSuccessCount() {
158    return loadSuccessCount;
159  }
160
161  /**
162   * Returns the number of times {@link Cache} lookup methods threw an exception while loading a
163   * new value. This is always incremented in conjunction with {@code missCount}, though
164   * {@code missCount} is also incremented when cache loading completes successfully (see
165   * {@link #loadSuccessCount}). Multiple concurrent misses for the same key will result in a
166   * single load operation.
167   */
168  public long loadExceptionCount() {
169    return loadExceptionCount;
170  }
171
172  /**
173   * Returns the ratio of cache loading attempts which threw exceptions. This is defined as
174   * {@code loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or
175   * {@code 0.0} when {@code loadSuccessCount + loadExceptionCount == 0}.
176   */
177  public double loadExceptionRate() {
178    long totalLoadCount = loadSuccessCount + loadExceptionCount;
179    return (totalLoadCount == 0)
180        ? 0.0
181        : (double) loadExceptionCount / totalLoadCount;
182  }
183
184  /**
185   * Returns the total number of nanoseconds the cache has spent loading new values. This can be
186   * used to calculate the miss penalty. This value is increased every time
187   * {@code loadSuccessCount} or {@code loadExceptionCount} is incremented.
188   */
189  public long totalLoadTime() {
190    return totalLoadTime;
191  }
192
193  /**
194   * Returns the average time spent loading new values. This is defined as
195   * {@code totalLoadTime / (loadSuccessCount + loadExceptionCount)}.
196   */
197  public double averageLoadPenalty() {
198    long totalLoadCount = loadSuccessCount + loadExceptionCount;
199    return (totalLoadCount == 0)
200        ? 0.0
201        : (double) totalLoadTime / totalLoadCount;
202  }
203
204  /**
205   * Returns the number of times an entry has been evicted. This count does not include manual
206   * {@linkplain Cache#invalidate invalidations}.
207   */
208  public long evictionCount() {
209    return evictionCount;
210  }
211
212  /**
213   * Returns a new {@code CacheStats} representing the difference between this {@code CacheStats}
214   * and {@code other}. Negative values, which aren't supported by {@code CacheStats} will be
215   * rounded up to zero.
216   */
217  public CacheStats minus(CacheStats other) {
218    return new CacheStats(
219        Math.max(0, hitCount - other.hitCount),
220        Math.max(0, missCount - other.missCount),
221        Math.max(0, loadSuccessCount - other.loadSuccessCount),
222        Math.max(0, loadExceptionCount - other.loadExceptionCount),
223        Math.max(0, totalLoadTime - other.totalLoadTime),
224        Math.max(0, evictionCount - other.evictionCount));
225  }
226
227  /**
228   * Returns a new {@code CacheStats} representing the sum of this {@code CacheStats}
229   * and {@code other}.
230   *
231   * @since 11.0
232   */
233  public CacheStats plus(CacheStats other) {
234    return new CacheStats(
235        hitCount + other.hitCount,
236        missCount + other.missCount,
237        loadSuccessCount + other.loadSuccessCount,
238        loadExceptionCount + other.loadExceptionCount,
239        totalLoadTime + other.totalLoadTime,
240        evictionCount + other.evictionCount);
241  }
242
243  @Override
244  public int hashCode() {
245    return Objects.hashCode(hitCount, missCount, loadSuccessCount, loadExceptionCount,
246        totalLoadTime, evictionCount);
247  }
248
249  @Override
250  public boolean equals(@Nullable Object object) {
251    if (object instanceof CacheStats) {
252      CacheStats other = (CacheStats) object;
253      return hitCount == other.hitCount
254          && missCount == other.missCount
255          && loadSuccessCount == other.loadSuccessCount
256          && loadExceptionCount == other.loadExceptionCount
257          && totalLoadTime == other.totalLoadTime
258          && evictionCount == other.evictionCount;
259    }
260    return false;
261  }
262
263  @Override
264  public String toString() {
265    return MoreObjects.toStringHelper(this)
266        .add("hitCount", hitCount)
267        .add("missCount", missCount)
268        .add("loadSuccessCount", loadSuccessCount)
269        .add("loadExceptionCount", loadExceptionCount)
270        .add("totalLoadTime", totalLoadTime)
271        .add("evictionCount", evictionCount)
272        .toString();
273  }
274}