1/*
2 * Copyright (C) 2009 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.cache;
18
19import static com.google.common.base.Objects.firstNonNull;
20import static com.google.common.base.Preconditions.checkArgument;
21import static com.google.common.base.Preconditions.checkNotNull;
22import static com.google.common.base.Preconditions.checkState;
23
24import com.google.common.annotations.Beta;
25import com.google.common.annotations.GwtCompatible;
26import com.google.common.annotations.GwtIncompatible;
27import com.google.common.base.Ascii;
28import com.google.common.base.Equivalence;
29import com.google.common.base.Equivalences;
30import com.google.common.base.Objects;
31import com.google.common.base.Supplier;
32import com.google.common.base.Suppliers;
33import com.google.common.base.Ticker;
34import com.google.common.cache.AbstractCache.SimpleStatsCounter;
35import com.google.common.cache.AbstractCache.StatsCounter;
36import com.google.common.cache.LocalCache.Strength;
37
38import java.lang.ref.SoftReference;
39import java.lang.ref.WeakReference;
40import java.util.ConcurrentModificationException;
41import java.util.concurrent.ConcurrentHashMap;
42import java.util.concurrent.TimeUnit;
43import java.util.logging.Level;
44import java.util.logging.Logger;
45
46import javax.annotation.CheckReturnValue;
47
48/**
49 * <p>A builder of {@link LoadingCache} and {@link Cache} instances having any combination of the
50 * following features:
51 *
52 * <ul>
53 * <li>automatic loading of entries into the cache
54 * <li>least-recently-used eviction when a maximum size is exceeded
55 * <li>time-based expiration of entries, measured since last access or last write
56 * <li>keys automatically wrapped in {@linkplain WeakReference weak} references
57 * <li>values automatically wrapped in {@linkplain WeakReference weak} or
58 *     {@linkplain SoftReference soft} references
59 * <li>notification of evicted (or otherwise removed) entries
60 * </ul>
61 *
62 * <p>Usage example: <pre>   {@code
63 *
64 *   LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
65 *       .maximumSize(10000)
66 *       .expireAfterWrite(10, TimeUnit.MINUTES)
67 *       .removalListener(MY_LISTENER)
68 *       .build(
69 *           new CacheLoader<Key, Graph>() {
70 *             public Graph load(Key key) throws AnyException {
71 *               return createExpensiveGraph(key);
72 *             }
73 *           });}</pre>
74 *
75 *
76 * These features are all optional.
77 *
78 * <p>The returned cache is implemented as a hash table with similar performance characteristics to
79 * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
80 * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
81 * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
82 * modify the cache after the iterator is created, it is undefined which of these changes, if any,
83 * are reflected in that iterator. These iterators never throw {@link
84 * ConcurrentModificationException}.
85 *
86 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the
87 * {@link Object#equals equals} method) to determine equality for keys or values. However, if
88 * {@link #weakKeys} was specified, the cache uses identity ({@code ==})
89 * comparisons instead for keys. Likewise, if {@link #weakValues} or {@link #softValues} was
90 * specified, the cache uses identity comparisons for values.
91 *
92 * <p>Entries are automatically evicted from the cache when any of
93 * {@linkplain #maximumSize(long) maximumSize}, {@linkplain #maximumWeight(long) maximumWeight},
94 * {@linkplain #expireAfterWrite expireAfterWrite},
95 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
96 * {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are requested.
97 *
98 * <p>If {@linkplain #maximumSize(long) maximumSize} or
99 * {@linkplain #maximumWeight(long) maximumWeight} is requested entries may be evicted on each cache
100 * modification.
101 *
102 * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or
103 * {@linkplain #expireAfterAccess expireAfterAccess} is requested entries may be evicted on each
104 * cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}. Expired
105 * entries may be counted in {@link Cache#size}, but will never be visible to read or write
106 * operations.
107 *
108 * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or
109 * {@linkplain #softValues softValues} are requested, it is possible for a key or value present in
110 * the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be
111 * removed from the cache on each cache modification, on occasional cache accesses, or on calls to
112 * {@link Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be
113 * visible to read or write operations.
114 *
115 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
116 * will be performed during write operations, or during occasional read operations in the absense of
117 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
118 * calling it should not be necessary with a high throughput cache. Only caches built with
119 * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
120 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
121 * {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic
122 * maintenance.
123 *
124 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
125 * retain all the configuration properties of the original cache. Note that the serialized form does
126 * <i>not</i> include cache contents, but only configuration.
127 *
128 * @param <K> the base key type for all caches created by this builder
129 * @param <V> the base value type for all caches created by this builder
130 * @author Charles Fry
131 * @author Kevin Bourrillion
132 * @since 10.0
133 */
134@Beta
135@GwtCompatible(emulated = true)
136public final class CacheBuilder<K, V> {
137  private static final int DEFAULT_INITIAL_CAPACITY = 16;
138  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
139  private static final int DEFAULT_EXPIRATION_NANOS = 0;
140  private static final int DEFAULT_REFRESH_NANOS = 0;
141
142  static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER = Suppliers.ofInstance(
143      new StatsCounter() {
144        @Override
145        public void recordHits(int count) {}
146
147        @Override
148        public void recordMisses(int count) {}
149
150        @Override
151        public void recordLoadSuccess(long loadTime) {}
152
153        @Override
154        public void recordLoadException(long loadTime) {}
155
156        @Override
157        public void recordEviction() {}
158
159        @Override
160        public CacheStats snapshot() {
161          return EMPTY_STATS;
162        }
163      });
164  static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
165
166  static final Supplier<SimpleStatsCounter> CACHE_STATS_COUNTER =
167      new Supplier<SimpleStatsCounter>() {
168    @Override
169    public SimpleStatsCounter get() {
170      return new SimpleStatsCounter();
171    }
172  };
173
174  enum NullListener implements RemovalListener<Object, Object> {
175    INSTANCE;
176
177    @Override
178    public void onRemoval(RemovalNotification<Object, Object> notification) {}
179  }
180
181  enum OneWeigher implements Weigher<Object, Object> {
182    INSTANCE;
183
184    @Override
185    public int weigh(Object key, Object value) {
186      return 1;
187    }
188  }
189
190  static final Ticker NULL_TICKER = new Ticker() {
191    @Override
192    public long read() {
193      return 0;
194    }
195  };
196
197  private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
198
199  static final int UNSET_INT = -1;
200
201  boolean strictParsing = true;
202
203  int initialCapacity = UNSET_INT;
204  int concurrencyLevel = UNSET_INT;
205  long maximumSize = UNSET_INT;
206  long maximumWeight = UNSET_INT;
207  Weigher<? super K, ? super V> weigher;
208
209  Strength keyStrength;
210  Strength valueStrength;
211
212  long expireAfterWriteNanos = UNSET_INT;
213  long expireAfterAccessNanos = UNSET_INT;
214  long refreshNanos = UNSET_INT;
215
216  Equivalence<Object> keyEquivalence;
217  Equivalence<Object> valueEquivalence;
218
219  RemovalListener<? super K, ? super V> removalListener;
220  Ticker ticker;
221
222  Supplier<? extends StatsCounter> statsCounterSupplier = CACHE_STATS_COUNTER;
223
224  // TODO(fry): make constructor private and update tests to use newBuilder
225  CacheBuilder() {}
226
227  /**
228   * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
229   * strong values, and no automatic eviction of any kind.
230   */
231  public static CacheBuilder<Object, Object> newBuilder() {
232    return new CacheBuilder<Object, Object>();
233  }
234
235  /**
236   * Enables lenient parsing. Useful for tests and spec parsing.
237   */
238  CacheBuilder<K, V> lenientParsing() {
239    strictParsing = false;
240    return this;
241  }
242
243  /**
244   * Sets a custom {@code Equivalence} strategy for comparing keys.
245   *
246   * <p>By default, the cache uses {@link Equivalences#identity} to determine key equality when
247   * {@link #weakKeys} is specified, and {@link Equivalences#equals()} otherwise.
248   */
249  CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
250    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
251    keyEquivalence = checkNotNull(equivalence);
252    return this;
253  }
254
255  Equivalence<Object> getKeyEquivalence() {
256    return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
257  }
258
259  /**
260   * Sets a custom {@code Equivalence} strategy for comparing values.
261   *
262   * <p>By default, the cache uses {@link Equivalences#identity} to determine value equality when
263   * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalences#equals()}
264   * otherwise.
265   */
266  CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
267    checkState(valueEquivalence == null,
268        "value equivalence was already set to %s", valueEquivalence);
269    this.valueEquivalence = checkNotNull(equivalence);
270    return this;
271  }
272
273  Equivalence<Object> getValueEquivalence() {
274    return firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
275  }
276
277  /**
278   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
279   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
280   * having a hash table of size eight. Providing a large enough estimate at construction time
281   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
282   * high wastes memory.
283   *
284   * @throws IllegalArgumentException if {@code initialCapacity} is negative
285   * @throws IllegalStateException if an initial capacity was already set
286   */
287  public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
288    checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
289        this.initialCapacity);
290    checkArgument(initialCapacity >= 0);
291    this.initialCapacity = initialCapacity;
292    return this;
293  }
294
295  int getInitialCapacity() {
296    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
297  }
298
299  /**
300   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
301   * table is internally partitioned to try to permit the indicated number of concurrent updates
302   * without contention. Because assignment of entries to these partitions is not necessarily
303   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
304   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
305   * higher value than you need can waste space and time, and a significantly lower value can lead
306   * to thread contention. But overestimates and underestimates within an order of magnitude do not
307   * usually have much noticeable impact. A value of one permits only one thread to modify the cache
308   * at a time, but since read operations can proceed concurrently, this still yields higher
309   * concurrency than full synchronization. Defaults to 4.
310   *
311   * <p><b>Note:</b>The default may change in the future. If you care about this value, you should
312   * always choose it explicitly.
313   *
314   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
315   * @throws IllegalStateException if a concurrency level was already set
316   */
317  public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
318    checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
319        this.concurrencyLevel);
320    checkArgument(concurrencyLevel > 0);
321    this.concurrencyLevel = concurrencyLevel;
322    return this;
323  }
324
325  int getConcurrencyLevel() {
326    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
327  }
328
329  /**
330   * Specifies the maximum number of entries the cache may contain. Note that the cache <b>may evict
331   * an entry before this limit is exceeded</b>. As the cache size grows close to the maximum, the
332   * cache evicts entries that are less likely to be used again. For example, the cache may evict an
333   * entry because it hasn't been used recently or very often.
334   *
335   * <p>When {@code size} is zero, elements will be evicted immediately after being loaded into the
336   * cache. This can be useful in testing, or to disable caching temporarily without a code change.
337   *
338   * @param size the maximum size of the cache
339   * @throws IllegalArgumentException if {@code size} is negative
340   * @throws IllegalStateException if a maximum size was already set
341   */
342  public CacheBuilder<K, V> maximumSize(long size) {
343    checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
344        this.maximumSize);
345    checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
346        this.maximumWeight);
347    checkState(this.weigher == null, "maximum size can not be combined with weigher");
348    checkArgument(size >= 0, "maximum size must not be negative");
349    this.maximumSize = size;
350    return this;
351  }
352
353  /**
354   * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
355   * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
356   * corresponding call to {@link #weigher} prior to calling {@link #build}.
357   *
358   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. As the cache
359   * size grows close to the maximum, the cache evicts entries that are less likely to be used
360   * again. For example, the cache may evict an entry because it hasn't been used recently or very
361   * often.
362   *
363   * <p>When {@code weight} is zero, elements will be evicted immediately after being loaded into
364   * cache. This can be useful in testing, or to disable caching temporarily without a code
365   * change.
366   *
367   * @param weight the maximum weight the cache may contain
368   * @throws IllegalArgumentException if {@code size} is negative
369   * @throws IllegalStateException if a maximum size was already set
370   * @since 11.0
371   */
372  public CacheBuilder<K, V> maximumWeight(long weight) {
373    checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
374        this.maximumWeight);
375    checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
376        this.maximumSize);
377    this.maximumWeight = weight;
378    checkArgument(weight >= 0, "maximum weight must not be negative");
379    return this;
380  }
381
382  /**
383   * Specifies the weigher to use in determining the weight of entries. Entry weight is taken
384   * into consideration by {@link #maximumWeight(long)} when determining which entries to evict, and
385   * use of this method requires a corresponding call to {@link #maximumWeight(long)} prior to
386   * calling {@link #build}. Weights are measured and recorded when entries are inserted into the
387   * cache, and are thus effectively static during the lifetime of a cache entry.
388   *
389   * <p>When the weight of an entry is zero it will not be considered for size-based eviction
390   * (though it still may be evicted by other means).
391   *
392   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
393   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
394   * original reference or the returned reference may be used to complete configuration and build
395   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
396   * building caches whose key or value types are incompatible with the types accepted by the
397   * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
398   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
399   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
400   *
401   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build
402   * a cache whose key or value type is incompatible with the weigher, you will likely experience
403   * a {@link ClassCastException} at some <i>undefined</i> point in the future.
404   *
405   * @param weigher the weigher to use in calculating the weight of cache entries
406   * @throws IllegalArgumentException if {@code size} is negative
407   * @throws IllegalStateException if a maximum size was already set
408   * @since 11.0
409   */
410  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
411      Weigher<? super K1, ? super V1> weigher) {
412    checkState(this.weigher == null);
413    if (strictParsing) {
414      checkState(this.maximumSize == UNSET_INT, "weigher can not be combined with maximum size",
415          this.maximumSize);
416    }
417
418    // safely limiting the kinds of caches this can produce
419    @SuppressWarnings("unchecked")
420    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
421    me.weigher = checkNotNull(weigher);
422    return me;
423  }
424
425  long getMaximumWeight() {
426    if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
427      return 0;
428    }
429    return (weigher == null) ? maximumSize : maximumWeight;
430  }
431
432  // Make a safe contravariant cast now so we don't have to do it over and over.
433  @SuppressWarnings("unchecked")
434  <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
435    return (Weigher<K1, V1>) Objects.firstNonNull(weigher, OneWeigher.INSTANCE);
436  }
437
438  /**
439   * Specifies that each key (not value) stored in the cache should be strongly referenced.
440   *
441   * @throws IllegalStateException if the key strength was already set
442   */
443  CacheBuilder<K, V> strongKeys() {
444    return setKeyStrength(Strength.STRONG);
445  }
446
447  /**
448   * Specifies that each key (not value) stored in the cache should be wrapped in a {@link
449   * WeakReference} (by default, strong references are used).
450   *
451   * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
452   * comparison to determine equality of keys.
453   *
454   * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size},
455   * but will never be visible to read or write operations; such entries are cleaned up as part of
456   * the routine maintenance described in the class javadoc.
457   *
458   * @throws IllegalStateException if the key strength was already set
459   */
460  @GwtIncompatible("java.lang.ref.WeakReference")
461  public CacheBuilder<K, V> weakKeys() {
462    return setKeyStrength(Strength.WEAK);
463  }
464
465  CacheBuilder<K, V> setKeyStrength(Strength strength) {
466    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
467    keyStrength = checkNotNull(strength);
468    return this;
469  }
470
471  Strength getKeyStrength() {
472    return firstNonNull(keyStrength, Strength.STRONG);
473  }
474
475  /**
476   * Specifies that each value (not key) stored in the cache should be strongly referenced.
477   *
478   * @throws IllegalStateException if the value strength was already set
479   */
480  CacheBuilder<K, V> strongValues() {
481    return setValueStrength(Strength.STRONG);
482  }
483
484  /**
485   * Specifies that each value (not key) stored in the cache should be wrapped in a
486   * {@link WeakReference} (by default, strong references are used).
487   *
488   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
489   * candidate for caching; consider {@link #softValues} instead.
490   *
491   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
492   * comparison to determine equality of values.
493   *
494   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
495   * but will never be visible to read or write operations; such entries are cleaned up as part of
496   * the routine maintenance described in the class javadoc.
497   *
498   * @throws IllegalStateException if the value strength was already set
499   */
500  @GwtIncompatible("java.lang.ref.WeakReference")
501  public CacheBuilder<K, V> weakValues() {
502    return setValueStrength(Strength.WEAK);
503  }
504
505  /**
506   * Specifies that each value (not key) stored in the cache should be wrapped in a
507   * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
508   * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
509   * demand.
510   *
511   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
512   * #maximumSize(long) maximum size} instead of using soft references. You should only use this
513   * method if you are well familiar with the practical consequences of soft references.
514   *
515   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
516   * comparison to determine equality of values.
517   *
518   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
519   * but will never be visible to read or write operations; such entries are cleaned up as part of
520   * the routine maintenance described in the class javadoc.
521   *
522   * @throws IllegalStateException if the value strength was already set
523   */
524  @GwtIncompatible("java.lang.ref.SoftReference")
525  public CacheBuilder<K, V> softValues() {
526    return setValueStrength(Strength.SOFT);
527  }
528
529  CacheBuilder<K, V> setValueStrength(Strength strength) {
530    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
531    valueStrength = checkNotNull(strength);
532    return this;
533  }
534
535  Strength getValueStrength() {
536    return firstNonNull(valueStrength, Strength.STRONG);
537  }
538
539  /**
540   * Specifies that each entry should be automatically removed from the cache once a fixed duration
541   * has elapsed after the entry's creation, or the most recent replacement of its value.
542   *
543   * <p>When {@code duration} is zero, this method hands off to
544   * {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
545   * size or weight. This can be useful in testing, or to disable caching temporarily without a code
546   * change.
547   *
548   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
549   * write operations. Expired entries are cleaned up as part of the routine maintenance described
550   * in the class javadoc.
551   *
552   * @param duration the length of time after an entry is created that it should be automatically
553   *     removed
554   * @param unit the unit that {@code duration} is expressed in
555   * @throws IllegalArgumentException if {@code duration} is negative
556   * @throws IllegalStateException if the time to live or time to idle was already set
557   */
558  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
559    checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
560        expireAfterWriteNanos);
561    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
562    this.expireAfterWriteNanos = unit.toNanos(duration);
563    return this;
564  }
565
566  long getExpireAfterWriteNanos() {
567    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
568  }
569
570  /**
571   * Specifies that each entry should be automatically removed from the cache once a fixed duration
572   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
573   * access. Access time is reset by all cache read and write operations (including
574   * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
575   * on the collection-views of {@link Cache#asMap}.
576   *
577   * <p>When {@code duration} is zero, this method hands off to
578   * {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
579   * size or weight. This can be useful in testing, or to disable caching temporarily without a code
580   * change.
581   *
582   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
583   * write operations. Expired entries are cleaned up as part of the routine maintenance described
584   * in the class javadoc.
585   *
586   * @param duration the length of time after an entry is last accessed that it should be
587   *     automatically removed
588   * @param unit the unit that {@code duration} is expressed in
589   * @throws IllegalArgumentException if {@code duration} is negative
590   * @throws IllegalStateException if the time to idle or time to live was already set
591   */
592  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
593    checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
594        expireAfterAccessNanos);
595    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
596    this.expireAfterAccessNanos = unit.toNanos(duration);
597    return this;
598  }
599
600  long getExpireAfterAccessNanos() {
601    return (expireAfterAccessNanos == UNSET_INT)
602        ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
603  }
604
605  /**
606   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
607   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
608   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling
609   * {@link CacheLoader#reload}.
610   *
611   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
612   * recommended that users of this method override {@link CacheLoader#reload} with an asynchrnous
613   * implementation; otherwise refreshes will block other cache operations.
614   *
615   * <p>Currently automatic refreshes are performed when the first stale request for an entry
616   * occurs. The request triggering refresh will make a blocking call to {@link CacheLoader#reload}
617   * and immediately return the new value if the returned future is complete, and the old value
618   * otherwise.
619   *
620   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
621   *
622   * @param duration the length of time after an entry is created that it should be considered
623   *     stale, and thus eligible for refresh
624   * @param unit the unit that {@code duration} is expressed in
625   * @throws IllegalArgumentException if {@code duration} is negative
626   * @throws IllegalStateException if the refresh interval was already set
627   * @since 11.0
628   */
629  @GwtIncompatible("To be supported")
630  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
631    checkNotNull(unit);
632    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
633    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
634    this.refreshNanos = unit.toNanos(duration);
635    return this;
636  }
637
638  long getRefreshNanos() {
639    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
640  }
641
642  /**
643   * Specifies a nanosecond-precision time source for use in determining when entries should be
644   * expired. By default, {@link System#nanoTime} is used.
645   *
646   * <p>The primary intent of this method is to facilitate testing of caches which have been
647   * configured with {@link #expireAfterWrite} or {@link #expireAfterAccess}.
648   *
649   * @throws IllegalStateException if a ticker was already set
650   */
651  @GwtIncompatible("To be supported")
652  public CacheBuilder<K, V> ticker(Ticker ticker) {
653    checkState(this.ticker == null);
654    this.ticker = checkNotNull(ticker);
655    return this;
656  }
657
658  Ticker getTicker(boolean recordsTime) {
659    if (ticker != null) {
660      return ticker;
661    }
662    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
663  }
664
665  /**
666   * Specifies a listener instance, which all caches built using this {@code CacheBuilder} will
667   * notify each time an entry is removed from the cache by any means.
668   *
669   * <p>Each cache built by this {@code CacheBuilder} after this method is called invokes the
670   * supplied listener after removing an element for any reason (see removal causes in {@link
671   * RemovalCause}). It will invoke the listener as part of the routine maintenance described
672   * in the class javadoc.
673   *
674   * <p><b>Note:</b> <i>all exceptions thrown by {@code listener} will be logged (using
675   * {@link java.util.logging.Logger})and then swallowed</i>.
676   *
677   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
678   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
679   * original reference or the returned reference may be used to complete configuration and build
680   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
681   * building caches whose key or value types are incompatible with the types accepted by the
682   * listener already provided; the {@code CacheBuilder} type cannot do this. For best results,
683   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
684   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
685   *
686   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build
687   * a cache whose key or value type is incompatible with the listener, you will likely experience
688   * a {@link ClassCastException} at some <i>undefined</i> point in the future.
689   *
690   * @throws IllegalStateException if a removal listener was already set
691   */
692  @CheckReturnValue
693  @GwtIncompatible("To be supported")
694  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
695      RemovalListener<? super K1, ? super V1> listener) {
696    checkState(this.removalListener == null);
697
698    // safely limiting the kinds of caches this can produce
699    @SuppressWarnings("unchecked")
700    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
701    me.removalListener = checkNotNull(listener);
702    return me;
703  }
704
705  // Make a safe contravariant cast now so we don't have to do it over and over.
706  @SuppressWarnings("unchecked")
707  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
708    return (RemovalListener<K1, V1>) Objects.firstNonNull(removalListener, NullListener.INSTANCE);
709  }
710
711  /**
712   * Disable the accumulation of {@link CacheStats} during the operation of the cache.
713   */
714  CacheBuilder<K, V> disableStats() {
715    checkState(statsCounterSupplier == CACHE_STATS_COUNTER);
716    statsCounterSupplier = NULL_STATS_COUNTER;
717    return this;
718  }
719
720  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
721    return statsCounterSupplier;
722  }
723
724  /**
725   * Builds a cache, which either returns an already-loaded value for a given key or atomically
726   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
727   * loading the value for this key, simply waits for that thread to finish and returns its
728   * loaded value. Note that multiple threads can concurrently load values for distinct keys.
729   *
730   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
731   * invoked again to create multiple independent caches.
732   *
733   * @param loader the cache loader used to obtain new values
734   * @return a cache having the requested features
735   */
736  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
737      CacheLoader<? super K1, V1> loader) {
738    checkWeightWithWeigher();
739    return new LocalCache.LocalLoadingCache<K1, V1>(this, loader);
740  }
741
742  /**
743   * Builds a cache which does not automatically load values when keys are requested.
744   *
745   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a
746   * {@code CacheLoader}.
747   *
748   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
749   * invoked again to create multiple independent caches.
750   *
751   * @return a cache having the requested features
752   * @since 11.0
753   */
754  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
755    checkWeightWithWeigher();
756    checkNonLoadingCache();
757    return new LocalCache.LocalManualCache<K1, V1>(this);
758  }
759
760  private void checkNonLoadingCache() {
761    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
762  }
763
764  private void checkWeightWithWeigher() {
765    if (weigher == null) {
766      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
767    } else {
768      if (strictParsing) {
769        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
770      } else {
771        if (maximumWeight == UNSET_INT) {
772          logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
773        }
774      }
775    }
776  }
777
778  /**
779   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
780   * string is not specified.
781   */
782  @Override
783  public String toString() {
784    Objects.ToStringHelper s = Objects.toStringHelper(this);
785    if (initialCapacity != UNSET_INT) {
786      s.add("initialCapacity", initialCapacity);
787    }
788    if (concurrencyLevel != UNSET_INT) {
789      s.add("concurrencyLevel", concurrencyLevel);
790    }
791    if (maximumWeight != UNSET_INT) {
792      if (weigher == null) {
793        s.add("maximumSize", maximumWeight);
794      } else {
795        s.add("maximumWeight", maximumWeight);
796      }
797    }
798    if (expireAfterWriteNanos != UNSET_INT) {
799      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
800    }
801    if (expireAfterAccessNanos != UNSET_INT) {
802      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
803    }
804    if (keyStrength != null) {
805      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
806    }
807    if (valueStrength != null) {
808      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
809    }
810    if (keyEquivalence != null) {
811      s.addValue("keyEquivalence");
812    }
813    if (valueEquivalence != null) {
814      s.addValue("valueEquivalence");
815    }
816    if (removalListener != null) {
817      s.addValue("removalListener");
818    }
819    return s.toString();
820  }
821}
822