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.Beta;
022import com.google.common.annotations.GwtCompatible;
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 on a query to {@link Cache#getIfPresent}.
050 * <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of
051 *     the cache.
052 * </ul>
053 * 
054 * <p>A lookup is specifically defined as an invocation of one of the methods 
055 * {@link LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)}, 
056 * {@link Cache#get(Object, Callable)}, or {@link LoadingCache#getAll(Iterable)}.
057 *
058 * @author Charles Fry
059 * @since 10.0
060 */
061@Beta
062@GwtCompatible
063public final class CacheStats {
064  private final long hitCount;
065  private final long missCount;
066  private final long loadSuccessCount;
067  private final long loadExceptionCount;
068  private final long totalLoadTime;
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  public CacheStats(long hitCount, long missCount, long loadSuccessCount,
078      long loadExceptionCount, long totalLoadTime, 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  /**
103   * Returns the number of times {@link Cache} lookup methods have returned a cached value.
104   */
105  public long hitCount() {
106    return hitCount;
107  }
108
109  /**
110   * Returns the ratio of cache requests which were hits. This is defined as
111   * {@code hitCount / requestCount}, or {@code 1.0} when {@code requestCount == 0}.
112   * Note that {@code hitRate + missRate =~ 1.0}.
113   */
114  public double hitRate() {
115    long requestCount = requestCount();
116    return (requestCount == 0) ? 1.0 : (double) hitCount / requestCount;
117  }
118
119  /**
120   * Returns the number of times {@link Cache} lookup methods have returned an uncached (newly
121   * loaded) value, or null. Multiple concurrent calls to {@link Cache} lookup methods on an absent
122   * value can result in multiple misses, all returning the results of a single cache load
123   * operation.
124   */
125  public long missCount() {
126    return missCount;
127  }
128
129  /**
130   * Returns the ratio of cache requests which were misses. This is defined as
131   * {@code missCount / requestCount}, or {@code 0.0} when {@code requestCount == 0}.
132   * Note that {@code hitRate + missRate =~ 1.0}. Cache misses include all requests which
133   * weren't cache hits, including requests which resulted in either successful or failed loading
134   * attempts, and requests which waited for other threads to finish loading. It is thus the case
135   * that {@code missCount &gt;= loadSuccessCount + loadExceptionCount}. Multiple
136   * concurrent misses for the same key will result in a single load operation.
137   */
138  public double missRate() {
139    long requestCount = requestCount();
140    return (requestCount == 0) ? 0.0 : (double) missCount / requestCount;
141  }
142
143  /**
144   * Returns the total number of times that {@link Cache} lookup methods attempted to load new
145   * values. This includes both successful load operations, as well as those that threw
146   * exceptions. This is defined as {@code loadSuccessCount + loadExceptionCount}.
147   */
148  public long loadCount() {
149    return loadSuccessCount + loadExceptionCount;
150  }
151
152  /**
153   * Returns the number of times {@link Cache} lookup methods have successfully loaded a new value.
154   * This is always incremented in conjunction with {@link #missCount}, though {@code missCount}
155   * is also incremented when an exception is encountered during cache loading (see
156   * {@link #loadExceptionCount}). Multiple concurrent misses for the same key will result in a
157   * single load operation.
158   */
159  public long loadSuccessCount() {
160    return loadSuccessCount;
161  }
162
163  /**
164   * Returns the number of times {@link Cache} lookup methods threw an exception while loading a
165   * new value. This is always incremented in conjunction with {@code missCount}, though
166   * {@code missCount} is also incremented when cache loading completes successfully (see
167   * {@link #loadSuccessCount}). Multiple concurrent misses for the same key will result in a
168   * single load operation.
169   */
170  public long loadExceptionCount() {
171    return loadExceptionCount;
172  }
173
174  /**
175   * Returns the ratio of cache loading attempts which threw exceptions. This is defined as
176   * {@code loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or
177   * {@code 0.0} when {@code loadSuccessCount + loadExceptionCount == 0}.
178   */
179  public double loadExceptionRate() {
180    long totalLoadCount = loadSuccessCount + loadExceptionCount;
181    return (totalLoadCount == 0)
182        ? 0.0
183        : (double) loadExceptionCount / totalLoadCount;
184  }
185
186  /**
187   * Returns the total number of nanoseconds the cache has spent loading new values. This can be
188   * used to calculate the miss penalty. This value is increased every time
189   * {@code loadSuccessCount} or {@code loadExceptionCount} is incremented.
190   */
191  public long totalLoadTime() {
192    return totalLoadTime;
193  }
194
195  /**
196   * Returns the average time spent loading new values. This is defined as
197   * {@code totalLoadTime / (loadSuccessCount + loadExceptionCount)}.
198   */
199  public double averageLoadPenalty() {
200    long totalLoadCount = loadSuccessCount + loadExceptionCount;
201    return (totalLoadCount == 0)
202        ? 0.0
203        : (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}
231   * and {@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(hitCount, missCount, loadSuccessCount, loadExceptionCount,
248        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 Objects.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}