001/*
002 * Copyright (C) 2009 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;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.base.Ascii;
024import com.google.common.base.Equivalence;
025import com.google.common.base.MoreObjects;
026import com.google.common.base.Supplier;
027import com.google.common.base.Suppliers;
028import com.google.common.base.Ticker;
029import com.google.common.cache.AbstractCache.SimpleStatsCounter;
030import com.google.common.cache.AbstractCache.StatsCounter;
031import com.google.common.cache.LocalCache.Strength;
032import java.lang.ref.SoftReference;
033import java.lang.ref.WeakReference;
034import java.util.ConcurrentModificationException;
035import java.util.concurrent.ConcurrentHashMap;
036import java.util.concurrent.TimeUnit;
037import java.util.logging.Level;
038import java.util.logging.Logger;
039import javax.annotation.CheckReturnValue;
040
041/**
042 * <p>A builder of {@link LoadingCache} and {@link Cache} instances having any combination of the
043 * following features:
044 *
045 * <ul>
046 * <li>automatic loading of entries into the cache
047 * <li>least-recently-used eviction when a maximum size is exceeded
048 * <li>time-based expiration of entries, measured since last access or last write
049 * <li>keys automatically wrapped in {@linkplain WeakReference weak} references
050 * <li>values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain SoftReference
051 *     soft} references
052 * <li>notification of evicted (or otherwise removed) entries
053 * <li>accumulation of cache access statistics
054 * </ul>
055 *
056 *
057 * <p>These features are all optional; caches can be created using all or none of them. By default
058 * cache instances created by {@code CacheBuilder} will not perform any type of eviction.
059 *
060 * <p>Usage example: <pre>   {@code
061 *
062 *   LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
063 *       .maximumSize(10000)
064 *       .expireAfterWrite(10, TimeUnit.MINUTES)
065 *       .removalListener(MY_LISTENER)
066 *       .build(
067 *           new CacheLoader<Key, Graph>() {
068 *             public Graph load(Key key) throws AnyException {
069 *               return createExpensiveGraph(key);
070 *             }
071 *           });}</pre>
072 *
073 * <p>Or equivalently, <pre>   {@code
074 *
075 *   // In real life this would come from a command-line flag or config file
076 *   String spec = "maximumSize=10000,expireAfterWrite=10m";
077 *
078 *   LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
079 *       .removalListener(MY_LISTENER)
080 *       .build(
081 *           new CacheLoader<Key, Graph>() {
082 *             public Graph load(Key key) throws AnyException {
083 *               return createExpensiveGraph(key);
084 *             }
085 *           });}</pre>
086 *
087 * <p>The returned cache is implemented as a hash table with similar performance characteristics to
088 * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
089 * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
090 * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
091 * modify the cache after the iterator is created, it is undefined which of these changes, if any,
092 * are reflected in that iterator. These iterators never throw
093 * {@link ConcurrentModificationException}.
094 *
095 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the
096 * {@link Object#equals equals} method) to determine equality for keys or values. However, if
097 * {@link #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for
098 * keys. Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses
099 * identity comparisons for values.
100 *
101 * <p>Entries are automatically evicted from the cache when any of {@linkplain #maximumSize(long)
102 * maximumSize}, {@linkplain #maximumWeight(long) maximumWeight}, {@linkplain #expireAfterWrite
103 * expireAfterWrite}, {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys
104 * weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are
105 * requested.
106 *
107 * <p>If {@linkplain #maximumSize(long) maximumSize} or {@linkplain #maximumWeight(long)
108 * maximumWeight} is requested entries may be evicted on each cache modification.
109 *
110 * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or {@linkplain #expireAfterAccess
111 * expireAfterAccess} is requested entries may be evicted on each cache modification, on occasional
112 * cache accesses, or on calls to {@link Cache#cleanUp}. Expired entries may be counted by
113 * {@link Cache#size}, but will never be visible to read or write operations.
114 *
115 * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or
116 * {@linkplain #softValues softValues} are requested, it is possible for a key or value present in
117 * the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be
118 * removed from the cache on each cache modification, on occasional cache accesses, or on calls to
119 * {@link Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be
120 * visible to read or write operations.
121 *
122 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
123 * will be performed during write operations, or during occasional read operations in the absence of
124 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
125 * calling it should not be necessary with a high throughput cache. Only caches built with
126 * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
127 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
128 * {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic
129 * maintenance.
130 *
131 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
132 * retain all the configuration properties of the original cache. Note that the serialized form does
133 * <i>not</i> include cache contents, but only configuration.
134 *
135 * <p>See the Guava User Guide article on
136 * <a href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level
137 * explanation.
138 *
139 * @param <K> the base key type for all caches created by this builder
140 * @param <V> the base value type for all caches created by this builder
141 * @author Charles Fry
142 * @author Kevin Bourrillion
143 * @since 10.0
144 */
145@GwtCompatible(emulated = true)
146public final class CacheBuilder<K, V> {
147  private static final int DEFAULT_INITIAL_CAPACITY = 16;
148  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
149  private static final int DEFAULT_EXPIRATION_NANOS = 0;
150  private static final int DEFAULT_REFRESH_NANOS = 0;
151
152  static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER =
153      Suppliers.ofInstance(
154          new StatsCounter() {
155            @Override
156            public void recordHits(int count) {}
157
158            @Override
159            public void recordMisses(int count) {}
160
161            @Override
162            public void recordLoadSuccess(long loadTime) {}
163
164            @Override
165            public void recordLoadException(long loadTime) {}
166
167            @Override
168            public void recordEviction() {}
169
170            @Override
171            public CacheStats snapshot() {
172              return EMPTY_STATS;
173            }
174          });
175  static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
176
177  static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
178      new Supplier<StatsCounter>() {
179        @Override
180        public StatsCounter get() {
181          return new SimpleStatsCounter();
182        }
183      };
184
185  enum NullListener implements RemovalListener<Object, Object> {
186    INSTANCE;
187
188    @Override
189    public void onRemoval(RemovalNotification<Object, Object> notification) {}
190  }
191
192  enum OneWeigher implements Weigher<Object, Object> {
193    INSTANCE;
194
195    @Override
196    public int weigh(Object key, Object value) {
197      return 1;
198    }
199  }
200
201  static final Ticker NULL_TICKER =
202      new Ticker() {
203        @Override
204        public long read() {
205          return 0;
206        }
207      };
208
209  private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
210
211  static final int UNSET_INT = -1;
212
213  boolean strictParsing = true;
214
215  int initialCapacity = UNSET_INT;
216  int concurrencyLevel = UNSET_INT;
217  long maximumSize = UNSET_INT;
218  long maximumWeight = UNSET_INT;
219  Weigher<? super K, ? super V> weigher;
220
221  Strength keyStrength;
222  Strength valueStrength;
223
224  long expireAfterWriteNanos = UNSET_INT;
225  long expireAfterAccessNanos = UNSET_INT;
226  long refreshNanos = UNSET_INT;
227
228  Equivalence<Object> keyEquivalence;
229  Equivalence<Object> valueEquivalence;
230
231  RemovalListener<? super K, ? super V> removalListener;
232  Ticker ticker;
233
234  Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
235
236  // TODO(fry): make constructor private and update tests to use newBuilder
237  CacheBuilder() {}
238
239  /**
240   * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
241   * strong values, and no automatic eviction of any kind.
242   */
243  public static CacheBuilder<Object, Object> newBuilder() {
244    return new CacheBuilder<Object, Object>();
245  }
246
247  /**
248   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
249   *
250   * @since 12.0
251   */
252  @GwtIncompatible // To be supported
253  public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
254    return spec.toCacheBuilder().lenientParsing();
255  }
256
257  /**
258   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
259   * This is especially useful for command-line configuration of a {@code CacheBuilder}.
260   *
261   * @param spec a String in the format specified by {@link CacheBuilderSpec}
262   * @since 12.0
263   */
264  @GwtIncompatible // To be supported
265  public static CacheBuilder<Object, Object> from(String spec) {
266    return from(CacheBuilderSpec.parse(spec));
267  }
268
269  /**
270   * Enables lenient parsing. Useful for tests and spec parsing.
271   *
272   * @return this {@code CacheBuilder} instance (for chaining)
273   */
274  @GwtIncompatible // To be supported
275  CacheBuilder<K, V> lenientParsing() {
276    strictParsing = false;
277    return this;
278  }
279
280  /**
281   * Sets a custom {@code Equivalence} strategy for comparing keys.
282   *
283   * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
284   * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
285   *
286   * @return this {@code CacheBuilder} instance (for chaining)
287   */
288  @GwtIncompatible // To be supported
289  CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
290    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
291    keyEquivalence = checkNotNull(equivalence);
292    return this;
293  }
294
295  Equivalence<Object> getKeyEquivalence() {
296    return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
297  }
298
299  /**
300   * Sets a custom {@code Equivalence} strategy for comparing values.
301   *
302   * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
303   * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
304   * otherwise.
305   *
306   * @return this {@code CacheBuilder} instance (for chaining)
307   */
308  @GwtIncompatible // To be supported
309  CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
310    checkState(
311        valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
312    this.valueEquivalence = checkNotNull(equivalence);
313    return this;
314  }
315
316  Equivalence<Object> getValueEquivalence() {
317    return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
318  }
319
320  /**
321   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
322   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
323   * having a hash table of size eight. Providing a large enough estimate at construction time
324   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
325   * high wastes memory.
326   *
327   * @return this {@code CacheBuilder} instance (for chaining)
328   * @throws IllegalArgumentException if {@code initialCapacity} is negative
329   * @throws IllegalStateException if an initial capacity was already set
330   */
331  public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
332    checkState(
333        this.initialCapacity == UNSET_INT,
334        "initial capacity was already set to %s",
335        this.initialCapacity);
336    checkArgument(initialCapacity >= 0);
337    this.initialCapacity = initialCapacity;
338    return this;
339  }
340
341  int getInitialCapacity() {
342    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
343  }
344
345  /**
346   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
347   * table is internally partitioned to try to permit the indicated number of concurrent updates
348   * without contention. Because assignment of entries to these partitions is not necessarily
349   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
350   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
351   * higher value than you need can waste space and time, and a significantly lower value can lead
352   * to thread contention. But overestimates and underestimates within an order of magnitude do not
353   * usually have much noticeable impact. A value of one permits only one thread to modify the cache
354   * at a time, but since read operations and cache loading computations can proceed concurrently,
355   * this still yields higher concurrency than full synchronization.
356   *
357   * <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
358   * value, you should always choose it explicitly.
359   *
360   * <p>The current implementation uses the concurrency level to create a fixed number of hashtable
361   * segments, each governed by its own write lock. The segment lock is taken once for each explicit
362   * write, and twice for each cache loading computation (once prior to loading the new value, and
363   * once after loading completes). Much internal cache management is performed at the segment
364   * granularity. For example, access queues and write queues are kept per segment when they are
365   * required by the selected eviction algorithm. As such, when writing unit tests it is not
366   * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
367   * behavior.
368   *
369   * <p>Note that future implementations may abandon segment locking in favor of more advanced
370   * concurrency controls.
371   *
372   * @return this {@code CacheBuilder} instance (for chaining)
373   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
374   * @throws IllegalStateException if a concurrency level was already set
375   */
376  public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
377    checkState(
378        this.concurrencyLevel == UNSET_INT,
379        "concurrency level was already set to %s",
380        this.concurrencyLevel);
381    checkArgument(concurrencyLevel > 0);
382    this.concurrencyLevel = concurrencyLevel;
383    return this;
384  }
385
386  int getConcurrencyLevel() {
387    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
388  }
389
390  /**
391   * Specifies the maximum number of entries the cache may contain.
392   *
393   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
394   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
395   * resulting segment inside the cache <i>independently</i> limits its own size to approximately
396   * {@code maximumSize / concurrencyLevel}.
397   *
398   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
399   * For example, the cache may evict an entry because it hasn't been used recently or very often.
400   *
401   * <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into
402   * cache. This can be useful in testing, or to disable caching temporarily.
403   *
404   * <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
405   *
406   * @param maximumSize the maximum size of the cache
407   * @return this {@code CacheBuilder} instance (for chaining)
408   * @throws IllegalArgumentException if {@code maximumSize} is negative
409   * @throws IllegalStateException if a maximum size or weight was already set
410   */
411  public CacheBuilder<K, V> maximumSize(long maximumSize) {
412    checkState(
413        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
414    checkState(
415        this.maximumWeight == UNSET_INT,
416        "maximum weight was already set to %s",
417        this.maximumWeight);
418    checkState(this.weigher == null, "maximum size can not be combined with weigher");
419    checkArgument(maximumSize >= 0, "maximum size must not be negative");
420    this.maximumSize = maximumSize;
421    return this;
422  }
423
424  /**
425   * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
426   * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
427   * corresponding call to {@link #weigher} prior to calling {@link #build}.
428   *
429   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
430   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
431   * resulting segment inside the cache <i>independently</i> limits its own weight to approximately
432   * {@code maximumWeight / concurrencyLevel}.
433   *
434   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
435   * For example, the cache may evict an entry because it hasn't been used recently or very often.
436   *
437   * <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
438   * into cache. This can be useful in testing, or to disable caching temporarily.
439   *
440   * <p>Note that weight is only used to determine whether the cache is over capacity; it has no
441   * effect on selecting which entry should be evicted next.
442   *
443   * <p>This feature cannot be used in conjunction with {@link #maximumSize}.
444   *
445   * @param maximumWeight the maximum total weight of entries the cache may contain
446   * @return this {@code CacheBuilder} instance (for chaining)
447   * @throws IllegalArgumentException if {@code maximumWeight} is negative
448   * @throws IllegalStateException if a maximum weight or size was already set
449   * @since 11.0
450   */
451  @GwtIncompatible // To be supported
452  public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
453    checkState(
454        this.maximumWeight == UNSET_INT,
455        "maximum weight was already set to %s",
456        this.maximumWeight);
457    checkState(
458        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
459    this.maximumWeight = maximumWeight;
460    checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
461    return this;
462  }
463
464  /**
465   * Specifies the weigher to use in determining the weight of entries. Entry weight is taken into
466   * consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use
467   * of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling
468   * {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and
469   * are thus effectively static during the lifetime of a cache entry.
470   *
471   * <p>When the weight of an entry is zero it will not be considered for size-based eviction
472   * (though it still may be evicted by other means).
473   *
474   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
475   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
476   * original reference or the returned reference may be used to complete configuration and build
477   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
478   * building caches whose key or value types are incompatible with the types accepted by the
479   * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
480   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
481   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
482   *
483   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a
484   * cache whose key or value type is incompatible with the weigher, you will likely experience a
485   * {@link ClassCastException} at some <i>undefined</i> point in the future.
486   *
487   * @param weigher the weigher to use in calculating the weight of cache entries
488   * @return this {@code CacheBuilder} instance (for chaining)
489   * @throws IllegalArgumentException if {@code size} is negative
490   * @throws IllegalStateException if a maximum size was already set
491   * @since 11.0
492   */
493  @GwtIncompatible // To be supported
494  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
495      Weigher<? super K1, ? super V1> weigher) {
496    checkState(this.weigher == null);
497    if (strictParsing) {
498      checkState(
499          this.maximumSize == UNSET_INT,
500          "weigher can not be combined with maximum size",
501          this.maximumSize);
502    }
503
504    // safely limiting the kinds of caches this can produce
505    @SuppressWarnings("unchecked")
506    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
507    me.weigher = checkNotNull(weigher);
508    return me;
509  }
510
511  long getMaximumWeight() {
512    if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
513      return 0;
514    }
515    return (weigher == null) ? maximumSize : maximumWeight;
516  }
517
518  // Make a safe contravariant cast now so we don't have to do it over and over.
519  @SuppressWarnings("unchecked")
520  <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
521    return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
522  }
523
524  /**
525   * Specifies that each key (not value) stored in the cache should be wrapped in a
526   * {@link WeakReference} (by default, strong references are used).
527   *
528   * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
529   * comparison to determine equality of keys.
530   *
531   * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but
532   * will never be visible to read or write operations; such entries are cleaned up as part of the
533   * routine maintenance described in the class javadoc.
534   *
535   * @return this {@code CacheBuilder} instance (for chaining)
536   * @throws IllegalStateException if the key strength was already set
537   */
538  @GwtIncompatible // java.lang.ref.WeakReference
539  public CacheBuilder<K, V> weakKeys() {
540    return setKeyStrength(Strength.WEAK);
541  }
542
543  CacheBuilder<K, V> setKeyStrength(Strength strength) {
544    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
545    keyStrength = checkNotNull(strength);
546    return this;
547  }
548
549  Strength getKeyStrength() {
550    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
551  }
552
553  /**
554   * Specifies that each value (not key) stored in the cache should be wrapped in a
555   * {@link WeakReference} (by default, strong references are used).
556   *
557   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
558   * candidate for caching; consider {@link #softValues} instead.
559   *
560   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
561   * comparison to determine equality of values.
562   *
563   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
564   * but will never be visible to read or write operations; such entries are cleaned up as part of
565   * the routine maintenance described in the class javadoc.
566   *
567   * @return this {@code CacheBuilder} instance (for chaining)
568   * @throws IllegalStateException if the value strength was already set
569   */
570  @GwtIncompatible // java.lang.ref.WeakReference
571  public CacheBuilder<K, V> weakValues() {
572    return setValueStrength(Strength.WEAK);
573  }
574
575  /**
576   * Specifies that each value (not key) stored in the cache should be wrapped in a
577   * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
578   * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
579   * demand.
580   *
581   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache
582   * {@linkplain #maximumSize(long) maximum size} instead of using soft references. You should only
583   * use this method if you are well familiar with the practical consequences of soft references.
584   *
585   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
586   * comparison to determine equality of values.
587   *
588   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
589   * but will never be visible to read or write operations; such entries are cleaned up as part of
590   * the routine maintenance described in the class javadoc.
591   *
592   * @return this {@code CacheBuilder} instance (for chaining)
593   * @throws IllegalStateException if the value strength was already set
594   */
595  @GwtIncompatible // java.lang.ref.SoftReference
596  public CacheBuilder<K, V> softValues() {
597    return setValueStrength(Strength.SOFT);
598  }
599
600  CacheBuilder<K, V> setValueStrength(Strength strength) {
601    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
602    valueStrength = checkNotNull(strength);
603    return this;
604  }
605
606  Strength getValueStrength() {
607    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
608  }
609
610  /**
611   * Specifies that each entry should be automatically removed from the cache once a fixed duration
612   * has elapsed after the entry's creation, or the most recent replacement of its value.
613   *
614   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
615   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
616   * useful in testing, or to disable caching temporarily without a code change.
617   *
618   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
619   * write operations. Expired entries are cleaned up as part of the routine maintenance described
620   * in the class javadoc.
621   *
622   * @param duration the length of time after an entry is created that it should be automatically
623   *     removed
624   * @param unit the unit that {@code duration} is expressed in
625   * @return this {@code CacheBuilder} instance (for chaining)
626   * @throws IllegalArgumentException if {@code duration} is negative
627   * @throws IllegalStateException if the time to live or time to idle was already set
628   */
629  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
630    checkState(
631        expireAfterWriteNanos == UNSET_INT,
632        "expireAfterWrite was already set to %s ns",
633        expireAfterWriteNanos);
634    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
635    this.expireAfterWriteNanos = unit.toNanos(duration);
636    return this;
637  }
638
639  long getExpireAfterWriteNanos() {
640    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
641  }
642
643  /**
644   * Specifies that each entry should be automatically removed from the cache once a fixed duration
645   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
646   * access. Access time is reset by all cache read and write operations (including
647   * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
648   * on the collection-views of {@link Cache#asMap}.
649   *
650   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
651   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
652   * useful in testing, or to disable caching temporarily without a code change.
653   *
654   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
655   * write operations. Expired entries are cleaned up as part of the routine maintenance described
656   * in the class javadoc.
657   *
658   * @param duration the length of time after an entry is last accessed that it should be
659   *     automatically removed
660   * @param unit the unit that {@code duration} is expressed in
661   * @return this {@code CacheBuilder} instance (for chaining)
662   * @throws IllegalArgumentException if {@code duration} is negative
663   * @throws IllegalStateException if the time to idle or time to live was already set
664   */
665  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
666    checkState(
667        expireAfterAccessNanos == UNSET_INT,
668        "expireAfterAccess was already set to %s ns",
669        expireAfterAccessNanos);
670    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
671    this.expireAfterAccessNanos = unit.toNanos(duration);
672    return this;
673  }
674
675  long getExpireAfterAccessNanos() {
676    return (expireAfterAccessNanos == UNSET_INT)
677        ? DEFAULT_EXPIRATION_NANOS
678        : expireAfterAccessNanos;
679  }
680
681  /**
682   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
683   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
684   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling
685   * {@link CacheLoader#reload}.
686   *
687   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
688   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
689   * implementation; otherwise refreshes will be performed during unrelated cache read and write
690   * operations.
691   *
692   * <p>Currently automatic refreshes are performed when the first stale request for an entry
693   * occurs. The request triggering refresh will make a blocking call to {@link CacheLoader#reload}
694   * and immediately return the new value if the returned future is complete, and the old value
695   * otherwise.
696   *
697   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
698   *
699   * @param duration the length of time after an entry is created that it should be considered
700   *     stale, and thus eligible for refresh
701   * @param unit the unit that {@code duration} is expressed in
702   * @return this {@code CacheBuilder} instance (for chaining)
703   * @throws IllegalArgumentException if {@code duration} is negative
704   * @throws IllegalStateException if the refresh interval was already set
705   * @since 11.0
706   */
707  @GwtIncompatible // To be supported (synchronously).
708  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
709    checkNotNull(unit);
710    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
711    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
712    this.refreshNanos = unit.toNanos(duration);
713    return this;
714  }
715
716  long getRefreshNanos() {
717    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
718  }
719
720  /**
721   * Specifies a nanosecond-precision time source for this cache. By default,
722   * {@link System#nanoTime} is used.
723   *
724   * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
725   * time source.
726   *
727   * @return this {@code CacheBuilder} instance (for chaining)
728   * @throws IllegalStateException if a ticker was already set
729   */
730  public CacheBuilder<K, V> ticker(Ticker ticker) {
731    checkState(this.ticker == null);
732    this.ticker = checkNotNull(ticker);
733    return this;
734  }
735
736  Ticker getTicker(boolean recordsTime) {
737    if (ticker != null) {
738      return ticker;
739    }
740    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
741  }
742
743  /**
744   * Specifies a listener instance that caches should notify each time an entry is removed for any
745   * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
746   * as part of the routine maintenance described in the class documentation above.
747   *
748   * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
749   * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
750   * same instance, but only the returned reference has the correct generic type information so as
751   * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in
752   * the class documentation above, configuring a builder and building your cache in a single
753   * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown
754   * by a cache operation at some <i>undefined</i> point in the future.
755   *
756   * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
757   * the {@code Cache} user, only logged via a {@link Logger}.
758   *
759   * @return the cache builder reference that should be used instead of {@code this} for any
760   *     remaining configuration and cache building
761   * @return this {@code CacheBuilder} instance (for chaining)
762   * @throws IllegalStateException if a removal listener was already set
763   */
764  @CheckReturnValue
765  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
766      RemovalListener<? super K1, ? super V1> listener) {
767    checkState(this.removalListener == null);
768
769    // safely limiting the kinds of caches this can produce
770    @SuppressWarnings("unchecked")
771    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
772    me.removalListener = checkNotNull(listener);
773    return me;
774  }
775
776  // Make a safe contravariant cast now so we don't have to do it over and over.
777  @SuppressWarnings("unchecked")
778  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
779    return (RemovalListener<K1, V1>)
780        MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
781  }
782
783  /**
784   * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
785   * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
786   * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
787   * cache operation.
788   *
789   * @return this {@code CacheBuilder} instance (for chaining)
790   * @since 12.0 (previously, stats collection was automatic)
791   */
792  public CacheBuilder<K, V> recordStats() {
793    statsCounterSupplier = CACHE_STATS_COUNTER;
794    return this;
795  }
796
797  boolean isRecordingStats() {
798    return statsCounterSupplier == CACHE_STATS_COUNTER;
799  }
800
801  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
802    return statsCounterSupplier;
803  }
804
805  /**
806   * Builds a cache, which either returns an already-loaded value for a given key or atomically
807   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
808   * loading the value for this key, simply waits for that thread to finish and returns its loaded
809   * value. Note that multiple threads can concurrently load values for distinct keys.
810   *
811   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
812   * invoked again to create multiple independent caches.
813   *
814   * @param loader the cache loader used to obtain new values
815   * @return a cache having the requested features
816   */
817  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
818      CacheLoader<? super K1, V1> loader) {
819    checkWeightWithWeigher();
820    return new LocalCache.LocalLoadingCache<K1, V1>(this, loader);
821  }
822
823  /**
824   * Builds a cache which does not automatically load values when keys are requested.
825   *
826   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a
827   * {@code CacheLoader}.
828   *
829   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
830   * invoked again to create multiple independent caches.
831   *
832   * @return a cache having the requested features
833   * @since 11.0
834   */
835  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
836    checkWeightWithWeigher();
837    checkNonLoadingCache();
838    return new LocalCache.LocalManualCache<K1, V1>(this);
839  }
840
841  private void checkNonLoadingCache() {
842    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
843  }
844
845  private void checkWeightWithWeigher() {
846    if (weigher == null) {
847      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
848    } else {
849      if (strictParsing) {
850        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
851      } else {
852        if (maximumWeight == UNSET_INT) {
853          logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
854        }
855      }
856    }
857  }
858
859  /**
860   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
861   * string is not specified.
862   */
863  @Override
864  public String toString() {
865    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
866    if (initialCapacity != UNSET_INT) {
867      s.add("initialCapacity", initialCapacity);
868    }
869    if (concurrencyLevel != UNSET_INT) {
870      s.add("concurrencyLevel", concurrencyLevel);
871    }
872    if (maximumSize != UNSET_INT) {
873      s.add("maximumSize", maximumSize);
874    }
875    if (maximumWeight != UNSET_INT) {
876      s.add("maximumWeight", maximumWeight);
877    }
878    if (expireAfterWriteNanos != UNSET_INT) {
879      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
880    }
881    if (expireAfterAccessNanos != UNSET_INT) {
882      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
883    }
884    if (keyStrength != null) {
885      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
886    }
887    if (valueStrength != null) {
888      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
889    }
890    if (keyEquivalence != null) {
891      s.addValue("keyEquivalence");
892    }
893    if (valueEquivalence != null) {
894      s.addValue("valueEquivalence");
895    }
896    if (removalListener != null) {
897      s.addValue("removalListener");
898    }
899    return s.toString();
900  }
901}