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 com.google.errorprone.annotations.CanIgnoreReturnValue;
033import com.google.j2objc.annotations.J2ObjCIncompatible;
034import java.lang.ref.SoftReference;
035import java.lang.ref.WeakReference;
036import java.util.ConcurrentModificationException;
037import java.util.IdentityHashMap;
038import java.util.Map;
039import java.util.concurrent.TimeUnit;
040import java.util.logging.Level;
041import java.util.logging.Logger;
042import javax.annotation.CheckForNull;
043
044/**
045 * A builder of {@link LoadingCache} and {@link Cache} instances.
046 *
047 * <h2>Prefer <a href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a> over Guava's caching
048 * API</h2>
049 *
050 * <p>The successor to Guava's caching API is <a
051 * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>. Its API is designed to make it a
052 * nearly drop-in replacement. It requires Java 8+, and is not available for Android or GWT/J2CL,
053 * and may have <a href="https://github.com/ben-manes/caffeine/wiki/Guava">different (usually
054 * better) behavior</a> when multiple threads attempt concurrent mutations. Its equivalent to {@code
055 * CacheBuilder} is its <a
056 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html">{@code
057 * Caffeine}</a> class. Caffeine offers better performance, more features (including asynchronous
058 * loading), and fewer <a
059 * href="https://github.com/google/guava/issues?q=is%3Aopen+is%3Aissue+label%3Apackage%3Dcache+label%3Atype%3Ddefect">bugs</a>.
060 *
061 * <p>Caffeine defines its own interfaces (<a
062 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Cache.html">{@code
063 * Cache}</a>, <a
064 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/LoadingCache.html">{@code
065 * LoadingCache}</a>, <a
066 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/CacheLoader.html">{@code
067 * CacheLoader}</a>, etc.), so you can use Caffeine without needing to use any Guava types.
068 * Caffeine's types are better than Guava's, especially for <a
069 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html">their
070 * deep support for asynchronous operations</a>. But if you want to migrate to Caffeine with minimal
071 * code changes, you can use <a
072 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/guava/latest/com.github.benmanes.caffeine.guava/com/github/benmanes/caffeine/guava/CaffeinatedGuava.html">its
073 * {@code CaffeinatedGuava} adapter class</a>, which lets you build a Guava {@code Cache} or a Guava
074 * {@code LoadingCache} backed by a Guava {@code CacheLoader}.
075 *
076 * <p>Caffeine's API for asynchronous operations uses {@code CompletableFuture}: <a
077 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html#get(K)">{@code
078 * AsyncLoadingCache.get}</a> returns a {@code CompletableFuture}, and implementations of <a
079 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncCacheLoader.html#asyncLoad(K,java.util.concurrent.Executor)">{@code
080 * AsyncCacheLoader.asyncLoad}</a> must return a {@code CompletableFuture}. Users of Guava's {@link
081 * com.google.common.util.concurrent.ListenableFuture} can adapt between the two {@code Future}
082 * types by using <a href="https://github.com/lukas-krecan/future-converter#java8-guava">{@code
083 * net.javacrumbs.futureconverter.java8guava.FutureConverter}</a>.
084 *
085 * <h2>More on {@code CacheBuilder}</h2>
086 *
087 * {@code CacheBuilder} builds caches with any combination of the following features:
088 *
089 * <ul>
090 *   <li>automatic loading of entries into the cache
091 *   <li>least-recently-used eviction when a maximum size is exceeded (note that the cache is
092 *       divided into segments, each of which does LRU internally)
093 *   <li>time-based expiration of entries, measured since last access or last write
094 *   <li>keys automatically wrapped in {@code WeakReference}
095 *   <li>values automatically wrapped in {@code WeakReference} or {@code SoftReference}
096 *   <li>notification of evicted (or otherwise removed) entries
097 *   <li>accumulation of cache access statistics
098 * </ul>
099 *
100 * <p>These features are all optional; caches can be created using all or none of them. By default,
101 * cache instances created by {@code CacheBuilder} will not perform any type of eviction.
102 *
103 * <p>Usage example:
104 *
105 * <pre>{@code
106 * LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
107 *     .maximumSize(10000)
108 *     .expireAfterWrite(Duration.ofMinutes(10))
109 *     .removalListener(MY_LISTENER)
110 *     .build(
111 *         new CacheLoader<Key, Graph>() {
112 *           public Graph load(Key key) throws AnyException {
113 *             return createExpensiveGraph(key);
114 *           }
115 *         });
116 * }</pre>
117 *
118 * <p>Or equivalently,
119 *
120 * <pre>{@code
121 * // In real life this would come from a command-line flag or config file
122 * String spec = "maximumSize=10000,expireAfterWrite=10m";
123 *
124 * LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
125 *     .removalListener(MY_LISTENER)
126 *     .build(
127 *         new CacheLoader<Key, Graph>() {
128 *           public Graph load(Key key) throws AnyException {
129 *             return createExpensiveGraph(key);
130 *           }
131 *         });
132 * }</pre>
133 *
134 * <p>The returned cache implements all optional operations of the {@link LoadingCache} and {@link
135 * Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly consistent
136 * iterators</i>. This means that they are safe for concurrent use, but if other threads modify the
137 * cache after the iterator is created, it is undefined which of these changes, if any, are
138 * reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}.
139 *
140 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
141 * Object#equals equals} method) to determine equality for keys or values. However, if {@link
142 * #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys.
143 * Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
144 * comparisons for values.
145 *
146 * <p>Entries are automatically evicted from the cache when any of {@link #maximumSize(long)
147 * maximumSize}, {@link #maximumWeight(long) maximumWeight}, {@link #expireAfterWrite
148 * expireAfterWrite}, {@link #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys},
149 * {@link #weakValues weakValues}, or {@link #softValues softValues} are requested.
150 *
151 * <p>If {@link #maximumSize(long) maximumSize} or {@link #maximumWeight(long) maximumWeight} is
152 * requested entries may be evicted on each cache modification.
153 *
154 * <p>If {@link #expireAfterWrite expireAfterWrite} or {@link #expireAfterAccess expireAfterAccess}
155 * is requested entries may be evicted on each cache modification, on occasional cache accesses, or
156 * on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link Cache#size}, but will
157 * never be visible to read or write operations.
158 *
159 * <p>If {@link #weakKeys weakKeys}, {@link #weakValues weakValues}, or {@link #softValues
160 * softValues} are requested, it is possible for a key or value present in the cache to be reclaimed
161 * by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on
162 * each cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}; such
163 * entries may be counted in {@link Cache#size}, but will never be visible to read or write
164 * operations.
165 *
166 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
167 * will be performed during write operations, or during occasional read operations in the absence of
168 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
169 * calling it should not be necessary with a high throughput cache. Only caches built with {@link
170 * #removalListener removalListener}, {@link #expireAfterWrite expireAfterWrite}, {@link
171 * #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, {@link #weakValues
172 * weakValues}, or {@link #softValues softValues} perform periodic maintenance.
173 *
174 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
175 * retain all the configuration properties of the original cache. Note that the serialized form does
176 * <i>not</i> include cache contents, but only configuration.
177 *
178 * <p>See the Guava User Guide article on <a
179 * href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level
180 * explanation.
181 *
182 * @param <K> the most general key type this builder will be able to create caches for. This is
183 *     normally {@code Object} unless it is constrained by using a method like {@code
184 *     #removalListener}. Cache keys may not be null.
185 * @param <V> the most general value type this builder will be able to create caches for. This is
186 *     normally {@code Object} unless it is constrained by using a method like {@code
187 *     #removalListener}. Cache values may not be null.
188 * @author Charles Fry
189 * @author Kevin Bourrillion
190 * @since 10.0
191 */
192@GwtCompatible(emulated = true)
193@ElementTypesAreNonnullByDefault
194public final class CacheBuilder<K, V> {
195  private static final int DEFAULT_INITIAL_CAPACITY = 16;
196  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
197
198  @SuppressWarnings("GoodTime") // should be a java.time.Duration
199  private static final int DEFAULT_EXPIRATION_NANOS = 0;
200
201  @SuppressWarnings("GoodTime") // should be a java.time.Duration
202  private static final int DEFAULT_REFRESH_NANOS = 0;
203
204  static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER =
205      Suppliers.ofInstance(
206          new StatsCounter() {
207            @Override
208            public void recordHits(int count) {}
209
210            @Override
211            public void recordMisses(int count) {}
212
213            @SuppressWarnings("GoodTime") // b/122668874
214            @Override
215            public void recordLoadSuccess(long loadTime) {}
216
217            @SuppressWarnings("GoodTime") // b/122668874
218            @Override
219            public void recordLoadException(long loadTime) {}
220
221            @Override
222            public void recordEviction() {}
223
224            @Override
225            public CacheStats snapshot() {
226              return EMPTY_STATS;
227            }
228          });
229  static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
230
231  /*
232   * We avoid using a method reference or lambda here for now:
233   *
234   * - method reference: Inside Google, CacheBuilder is used from the implementation of a custom
235   *   ClassLoader that is sometimes used as a system classloader. That's a problem because
236   *   method-reference linking tries to look up the system classloader, and it fails because there
237   *   isn't one yet.
238   *
239   * - lambda: Outside Google, we got a report of a similar problem in
240   *   https://github.com/google/guava/issues/6565
241   */
242  @SuppressWarnings("AnonymousToLambda")
243  static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
244      new Supplier<StatsCounter>() {
245        @Override
246        public StatsCounter get() {
247          return new SimpleStatsCounter();
248        }
249      };
250
251  enum NullListener implements RemovalListener<Object, Object> {
252    INSTANCE;
253
254    @Override
255    public void onRemoval(RemovalNotification<Object, Object> notification) {}
256  }
257
258  enum OneWeigher implements Weigher<Object, Object> {
259    INSTANCE;
260
261    @Override
262    public int weigh(Object key, Object value) {
263      return 1;
264    }
265  }
266
267  static final Ticker NULL_TICKER =
268      new Ticker() {
269        @Override
270        public long read() {
271          return 0;
272        }
273      };
274
275  // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566
276  private static final class LoggerHolder {
277    static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
278  }
279
280  static final int UNSET_INT = -1;
281
282  boolean strictParsing = true;
283
284  int initialCapacity = UNSET_INT;
285  int concurrencyLevel = UNSET_INT;
286  long maximumSize = UNSET_INT;
287  long maximumWeight = UNSET_INT;
288  @CheckForNull Weigher<? super K, ? super V> weigher;
289
290  @CheckForNull Strength keyStrength;
291  @CheckForNull Strength valueStrength;
292
293  @SuppressWarnings("GoodTime") // should be a java.time.Duration
294  long expireAfterWriteNanos = UNSET_INT;
295
296  @SuppressWarnings("GoodTime") // should be a java.time.Duration
297  long expireAfterAccessNanos = UNSET_INT;
298
299  @SuppressWarnings("GoodTime") // should be a java.time.Duration
300  long refreshNanos = UNSET_INT;
301
302  @CheckForNull Equivalence<Object> keyEquivalence;
303  @CheckForNull Equivalence<Object> valueEquivalence;
304
305  @CheckForNull RemovalListener<? super K, ? super V> removalListener;
306  @CheckForNull Ticker ticker;
307
308  Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
309
310  private CacheBuilder() {}
311
312  /**
313   * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
314   * strong values, and no automatic eviction of any kind.
315   *
316   * <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
317   * the {@link #build} methods allow you to create a cache of any key and value type desired.
318   */
319  public static CacheBuilder<Object, Object> newBuilder() {
320    return new CacheBuilder<>();
321  }
322
323  /**
324   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
325   *
326   * @since 12.0
327   */
328  @GwtIncompatible // To be supported
329  public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
330    return spec.toCacheBuilder().lenientParsing();
331  }
332
333  /**
334   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
335   * This is especially useful for command-line configuration of a {@code CacheBuilder}.
336   *
337   * @param spec a String in the format specified by {@link CacheBuilderSpec}
338   * @since 12.0
339   */
340  @GwtIncompatible // To be supported
341  public static CacheBuilder<Object, Object> from(String spec) {
342    return from(CacheBuilderSpec.parse(spec));
343  }
344
345  /**
346   * Enables lenient parsing. Useful for tests and spec parsing.
347   *
348   * @return this {@code CacheBuilder} instance (for chaining)
349   */
350  @GwtIncompatible // To be supported
351  @CanIgnoreReturnValue
352  CacheBuilder<K, V> lenientParsing() {
353    strictParsing = false;
354    return this;
355  }
356
357  /**
358   * Sets a custom {@code Equivalence} strategy for comparing keys.
359   *
360   * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
361   * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
362   *
363   * @return this {@code CacheBuilder} instance (for chaining)
364   */
365  @GwtIncompatible // To be supported
366  @CanIgnoreReturnValue
367  CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
368    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
369    keyEquivalence = checkNotNull(equivalence);
370    return this;
371  }
372
373  Equivalence<Object> getKeyEquivalence() {
374    return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
375  }
376
377  /**
378   * Sets a custom {@code Equivalence} strategy for comparing values.
379   *
380   * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
381   * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
382   * otherwise.
383   *
384   * @return this {@code CacheBuilder} instance (for chaining)
385   */
386  @GwtIncompatible // To be supported
387  @CanIgnoreReturnValue
388  CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
389    checkState(
390        valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
391    this.valueEquivalence = checkNotNull(equivalence);
392    return this;
393  }
394
395  Equivalence<Object> getValueEquivalence() {
396    return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
397  }
398
399  /**
400   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
401   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
402   * having a hash table of size eight. Providing a large enough estimate at construction time
403   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
404   * high wastes memory.
405   *
406   * @return this {@code CacheBuilder} instance (for chaining)
407   * @throws IllegalArgumentException if {@code initialCapacity} is negative
408   * @throws IllegalStateException if an initial capacity was already set
409   */
410  @CanIgnoreReturnValue
411  public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
412    checkState(
413        this.initialCapacity == UNSET_INT,
414        "initial capacity was already set to %s",
415        this.initialCapacity);
416    checkArgument(initialCapacity >= 0);
417    this.initialCapacity = initialCapacity;
418    return this;
419  }
420
421  int getInitialCapacity() {
422    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
423  }
424
425  /**
426   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
427   * table is internally partitioned to try to permit the indicated number of concurrent updates
428   * without contention. Because assignment of entries to these partitions is not necessarily
429   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
430   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
431   * higher value than you need can waste space and time, and a significantly lower value can lead
432   * to thread contention. But overestimates and underestimates within an order of magnitude do not
433   * usually have much noticeable impact. A value of one permits only one thread to modify the cache
434   * at a time, but since read operations and cache loading computations can proceed concurrently,
435   * this still yields higher concurrency than full synchronization.
436   *
437   * <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
438   * value, you should always choose it explicitly.
439   *
440   * <p>The current implementation uses the concurrency level to create a fixed number of hashtable
441   * segments, each governed by its own write lock. The segment lock is taken once for each explicit
442   * write, and twice for each cache loading computation (once prior to loading the new value, and
443   * once after loading completes). Much internal cache management is performed at the segment
444   * granularity. For example, access queues and write queues are kept per segment when they are
445   * required by the selected eviction algorithm. As such, when writing unit tests it is not
446   * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
447   * behavior.
448   *
449   * <p>Note that future implementations may abandon segment locking in favor of more advanced
450   * concurrency controls.
451   *
452   * @return this {@code CacheBuilder} instance (for chaining)
453   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
454   * @throws IllegalStateException if a concurrency level was already set
455   */
456  @CanIgnoreReturnValue
457  public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
458    checkState(
459        this.concurrencyLevel == UNSET_INT,
460        "concurrency level was already set to %s",
461        this.concurrencyLevel);
462    checkArgument(concurrencyLevel > 0);
463    this.concurrencyLevel = concurrencyLevel;
464    return this;
465  }
466
467  int getConcurrencyLevel() {
468    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
469  }
470
471  /**
472   * Specifies the maximum number of entries the cache may contain.
473   *
474   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
475   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
476   * resulting segment inside the cache <i>independently</i> limits its own size to approximately
477   * {@code maximumSize / concurrencyLevel}.
478   *
479   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
480   * For example, the cache may evict an entry because it hasn't been used recently or very often.
481   *
482   * <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into
483   * cache. This can be useful in testing, or to disable caching temporarily.
484   *
485   * <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
486   *
487   * @param maximumSize the maximum size of the cache
488   * @return this {@code CacheBuilder} instance (for chaining)
489   * @throws IllegalArgumentException if {@code maximumSize} is negative
490   * @throws IllegalStateException if a maximum size or weight was already set
491   */
492  @CanIgnoreReturnValue
493  public CacheBuilder<K, V> maximumSize(long maximumSize) {
494    checkState(
495        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
496    checkState(
497        this.maximumWeight == UNSET_INT,
498        "maximum weight was already set to %s",
499        this.maximumWeight);
500    checkState(this.weigher == null, "maximum size can not be combined with weigher");
501    checkArgument(maximumSize >= 0, "maximum size must not be negative");
502    this.maximumSize = maximumSize;
503    return this;
504  }
505
506  /**
507   * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
508   * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
509   * corresponding call to {@link #weigher} prior to calling {@link #build}.
510   *
511   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
512   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
513   * resulting segment inside the cache <i>independently</i> limits its own weight to approximately
514   * {@code maximumWeight / concurrencyLevel}.
515   *
516   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
517   * For example, the cache may evict an entry because it hasn't been used recently or very often.
518   *
519   * <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
520   * into cache. This can be useful in testing, or to disable caching temporarily.
521   *
522   * <p>Note that weight is only used to determine whether the cache is over capacity; it has no
523   * effect on selecting which entry should be evicted next.
524   *
525   * <p>This feature cannot be used in conjunction with {@link #maximumSize}.
526   *
527   * @param maximumWeight the maximum total weight of entries the cache may contain
528   * @return this {@code CacheBuilder} instance (for chaining)
529   * @throws IllegalArgumentException if {@code maximumWeight} is negative
530   * @throws IllegalStateException if a maximum weight or size was already set
531   * @since 11.0
532   */
533  @GwtIncompatible // To be supported
534  @CanIgnoreReturnValue
535  public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
536    checkState(
537        this.maximumWeight == UNSET_INT,
538        "maximum weight was already set to %s",
539        this.maximumWeight);
540    checkState(
541        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
542    checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
543    this.maximumWeight = maximumWeight;
544    return this;
545  }
546
547  /**
548   * Specifies the weigher to use in determining the weight of entries. Entry weight is taken into
549   * consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use
550   * of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling
551   * {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and
552   * are thus effectively static during the lifetime of a cache entry.
553   *
554   * <p>When the weight of an entry is zero it will not be considered for size-based eviction
555   * (though it still may be evicted by other means).
556   *
557   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
558   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
559   * original reference or the returned reference may be used to complete configuration and build
560   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
561   * building caches whose key or value types are incompatible with the types accepted by the
562   * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
563   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
564   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
565   *
566   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a
567   * cache whose key or value type is incompatible with the weigher, you will likely experience a
568   * {@link ClassCastException} at some <i>undefined</i> point in the future.
569   *
570   * @param weigher the weigher to use in calculating the weight of cache entries
571   * @return this {@code CacheBuilder} instance (for chaining)
572   * @throws IllegalStateException if a weigher was already set or {@link #maximumSize} was
573   *     previously called
574   * @since 11.0
575   */
576  @GwtIncompatible // To be supported
577  @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
578  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
579      Weigher<? super K1, ? super V1> weigher) {
580    checkState(this.weigher == null);
581    if (strictParsing) {
582      checkState(
583          this.maximumSize == UNSET_INT,
584          "weigher can not be combined with maximum size (%s provided)",
585          this.maximumSize);
586    }
587
588    // safely limiting the kinds of caches this can produce
589    @SuppressWarnings("unchecked")
590    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
591    me.weigher = checkNotNull(weigher);
592    return me;
593  }
594
595  long getMaximumWeight() {
596    if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
597      return 0;
598    }
599    return (weigher == null) ? maximumSize : maximumWeight;
600  }
601
602  // Make a safe contravariant cast now so we don't have to do it over and over.
603  @SuppressWarnings("unchecked")
604  <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
605    return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
606  }
607
608  /**
609   * Specifies that each key (not value) stored in the cache should be wrapped in a {@link
610   * WeakReference} (by default, strong references are used).
611   *
612   * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
613   * comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore
614   * technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap}
615   * does).
616   *
617   * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but
618   * will never be visible to read or write operations; such entries are cleaned up as part of the
619   * routine maintenance described in the class javadoc.
620   *
621   * @return this {@code CacheBuilder} instance (for chaining)
622   * @throws IllegalStateException if the key strength was already set
623   */
624  @GwtIncompatible // java.lang.ref.WeakReference
625  @CanIgnoreReturnValue
626  public CacheBuilder<K, V> weakKeys() {
627    return setKeyStrength(Strength.WEAK);
628  }
629
630  @CanIgnoreReturnValue
631  CacheBuilder<K, V> setKeyStrength(Strength strength) {
632    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
633    keyStrength = checkNotNull(strength);
634    return this;
635  }
636
637  Strength getKeyStrength() {
638    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
639  }
640
641  /**
642   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
643   * WeakReference} (by default, strong references are used).
644   *
645   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
646   * candidate for caching; consider {@link #softValues} instead.
647   *
648   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
649   * comparison to determine equality of values.
650   *
651   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
652   * but will never be visible to read or write operations; such entries are cleaned up as part of
653   * the routine maintenance described in the class javadoc.
654   *
655   * @return this {@code CacheBuilder} instance (for chaining)
656   * @throws IllegalStateException if the value strength was already set
657   */
658  @GwtIncompatible // java.lang.ref.WeakReference
659  @CanIgnoreReturnValue
660  public CacheBuilder<K, V> weakValues() {
661    return setValueStrength(Strength.WEAK);
662  }
663
664  /**
665   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
666   * SoftReference} (by default, strong references are used). Softly-referenced objects will be
667   * garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
668   * demand.
669   *
670   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
671   * #maximumSize(long) maximum size} instead of using soft references. You should only use this
672   * method if you are well familiar with the practical consequences of soft references.
673   *
674   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
675   * comparison to determine equality of values.
676   *
677   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
678   * but will never be visible to read or write operations; such entries are cleaned up as part of
679   * the routine maintenance described in the class javadoc.
680   *
681   * @return this {@code CacheBuilder} instance (for chaining)
682   * @throws IllegalStateException if the value strength was already set
683   */
684  @GwtIncompatible // java.lang.ref.SoftReference
685  @CanIgnoreReturnValue
686  public CacheBuilder<K, V> softValues() {
687    return setValueStrength(Strength.SOFT);
688  }
689
690  @CanIgnoreReturnValue
691  CacheBuilder<K, V> setValueStrength(Strength strength) {
692    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
693    valueStrength = checkNotNull(strength);
694    return this;
695  }
696
697  Strength getValueStrength() {
698    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
699  }
700
701  /**
702   * Specifies that each entry should be automatically removed from the cache once a fixed duration
703   * has elapsed after the entry's creation, or the most recent replacement of its value.
704   *
705   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
706   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
707   * useful in testing, or to disable caching temporarily without a code change.
708   *
709   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
710   * write operations. Expired entries are cleaned up as part of the routine maintenance described
711   * in the class javadoc.
712   *
713   * @param duration the length of time after an entry is created that it should be automatically
714   *     removed
715   * @return this {@code CacheBuilder} instance (for chaining)
716   * @throws IllegalArgumentException if {@code duration} is negative
717   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
718   * @throws ArithmeticException for durations greater than +/- approximately 292 years
719   * @since 25.0
720   */
721  @J2ObjCIncompatible
722  @GwtIncompatible // java.time.Duration
723  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
724  @CanIgnoreReturnValue
725  public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) {
726    return expireAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
727  }
728
729  /**
730   * Specifies that each entry should be automatically removed from the cache once a fixed duration
731   * has elapsed after the entry's creation, or the most recent replacement of its value.
732   *
733   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
734   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
735   * useful in testing, or to disable caching temporarily without a code change.
736   *
737   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
738   * write operations. Expired entries are cleaned up as part of the routine maintenance described
739   * in the class javadoc.
740   *
741   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
742   * when feasible), use {@link #expireAfterWrite(Duration)} instead.
743   *
744   * @param duration the length of time after an entry is created that it should be automatically
745   *     removed
746   * @param unit the unit that {@code duration} is expressed in
747   * @return this {@code CacheBuilder} instance (for chaining)
748   * @throws IllegalArgumentException if {@code duration} is negative
749   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
750   */
751  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
752  @CanIgnoreReturnValue
753  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
754    checkState(
755        expireAfterWriteNanos == UNSET_INT,
756        "expireAfterWrite was already set to %s ns",
757        expireAfterWriteNanos);
758    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
759    this.expireAfterWriteNanos = unit.toNanos(duration);
760    return this;
761  }
762
763  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
764  long getExpireAfterWriteNanos() {
765    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
766  }
767
768  /**
769   * Specifies that each entry should be automatically removed from the cache once a fixed duration
770   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
771   * access. Access time is reset by all cache read and write operations (including {@code
772   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
773   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}}. So,
774   * for example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for
775   * the entries you retrieve.
776   *
777   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
778   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
779   * useful in testing, or to disable caching temporarily without a code change.
780   *
781   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
782   * write operations. Expired entries are cleaned up as part of the routine maintenance described
783   * in the class javadoc.
784   *
785   * @param duration the length of time after an entry is last accessed that it should be
786   *     automatically removed
787   * @return this {@code CacheBuilder} instance (for chaining)
788   * @throws IllegalArgumentException if {@code duration} is negative
789   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
790   * @throws ArithmeticException for durations greater than +/- approximately 292 years
791   * @since 25.0
792   */
793  @J2ObjCIncompatible
794  @GwtIncompatible // java.time.Duration
795  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
796  @CanIgnoreReturnValue
797  public CacheBuilder<K, V> expireAfterAccess(java.time.Duration duration) {
798    return expireAfterAccess(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
799  }
800
801  /**
802   * Specifies that each entry should be automatically removed from the cache once a fixed duration
803   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
804   * access. Access time is reset by all cache read and write operations (including {@code
805   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
806   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for
807   * example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the
808   * entries you retrieve.
809   *
810   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
811   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
812   * useful in testing, or to disable caching temporarily without a code change.
813   *
814   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
815   * write operations. Expired entries are cleaned up as part of the routine maintenance described
816   * in the class javadoc.
817   *
818   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
819   * when feasible), use {@link #expireAfterAccess(Duration)} instead.
820   *
821   * @param duration the length of time after an entry is last accessed that it should be
822   *     automatically removed
823   * @param unit the unit that {@code duration} is expressed in
824   * @return this {@code CacheBuilder} instance (for chaining)
825   * @throws IllegalArgumentException if {@code duration} is negative
826   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
827   */
828  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
829  @CanIgnoreReturnValue
830  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
831    checkState(
832        expireAfterAccessNanos == UNSET_INT,
833        "expireAfterAccess was already set to %s ns",
834        expireAfterAccessNanos);
835    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
836    this.expireAfterAccessNanos = unit.toNanos(duration);
837    return this;
838  }
839
840  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
841  long getExpireAfterAccessNanos() {
842    return (expireAfterAccessNanos == UNSET_INT)
843        ? DEFAULT_EXPIRATION_NANOS
844        : expireAfterAccessNanos;
845  }
846
847  /**
848   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
849   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
850   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
851   * CacheLoader#reload}.
852   *
853   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
854   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
855   * implementation; otherwise refreshes will be performed during unrelated cache read and write
856   * operations.
857   *
858   * <p>Currently automatic refreshes are performed when the first stale request for an entry
859   * occurs. The request triggering refresh will make a synchronous call to {@link
860   * CacheLoader#reload}
861   * to obtain a future of the new value. If the returned future is already complete, it is returned
862   * immediately. Otherwise, the old value is returned.
863   *
864   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
865   *
866   * @param duration the length of time after an entry is created that it should be considered
867   *     stale, and thus eligible for refresh
868   * @return this {@code CacheBuilder} instance (for chaining)
869   * @throws IllegalArgumentException if {@code duration} is negative
870   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
871   * @throws ArithmeticException for durations greater than +/- approximately 292 years
872   * @since 25.0
873   */
874  @J2ObjCIncompatible
875  @GwtIncompatible // java.time.Duration
876  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
877  @CanIgnoreReturnValue
878  public CacheBuilder<K, V> refreshAfterWrite(java.time.Duration duration) {
879    return refreshAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
880  }
881
882  /**
883   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
884   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
885   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
886   * CacheLoader#reload}.
887   *
888   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
889   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
890   * implementation; otherwise refreshes will be performed during unrelated cache read and write
891   * operations.
892   *
893   * <p>Currently automatic refreshes are performed when the first stale request for an entry
894   * occurs. The request triggering refresh will make a synchronous call to {@link
895   * CacheLoader#reload}
896   * and immediately return the new value if the returned future is complete, and the old value
897   * otherwise.
898   *
899   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
900   *
901   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
902   * when feasible), use {@link #refreshAfterWrite(Duration)} instead.
903   *
904   * @param duration the length of time after an entry is created that it should be considered
905   *     stale, and thus eligible for refresh
906   * @param unit the unit that {@code duration} is expressed in
907   * @return this {@code CacheBuilder} instance (for chaining)
908   * @throws IllegalArgumentException if {@code duration} is negative
909   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
910   * @since 11.0
911   */
912  @GwtIncompatible // To be supported (synchronously).
913  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
914  @CanIgnoreReturnValue
915  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
916    checkNotNull(unit);
917    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
918    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
919    this.refreshNanos = unit.toNanos(duration);
920    return this;
921  }
922
923  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
924  long getRefreshNanos() {
925    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
926  }
927
928  /**
929   * Specifies a nanosecond-precision time source for this cache. By default, {@link
930   * System#nanoTime} is used.
931   *
932   * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
933   * time source.
934   *
935   * @return this {@code CacheBuilder} instance (for chaining)
936   * @throws IllegalStateException if a ticker was already set
937   */
938  @CanIgnoreReturnValue
939  public CacheBuilder<K, V> ticker(Ticker ticker) {
940    checkState(this.ticker == null);
941    this.ticker = checkNotNull(ticker);
942    return this;
943  }
944
945  Ticker getTicker(boolean recordsTime) {
946    if (ticker != null) {
947      return ticker;
948    }
949    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
950  }
951
952  /**
953   * Specifies a listener instance that caches should notify each time an entry is removed for any
954   * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
955   * as part of the routine maintenance described in the class documentation above.
956   *
957   * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
958   * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
959   * same instance, but only the returned reference has the correct generic type information to
960   * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the
961   * class documentation above, configuring a builder and building your cache in a single statement.
962   * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache
963   * operation at some <i>undefined</i> point in the future.
964   *
965   * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
966   * the {@code Cache} user, only logged via a {@link Logger}.
967   *
968   * @return the cache builder reference that should be used instead of {@code this} for any
969   *     remaining configuration and cache building
970   * @return this {@code CacheBuilder} instance (for chaining)
971   * @throws IllegalStateException if a removal listener was already set
972   */
973  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
974      RemovalListener<? super K1, ? super V1> listener) {
975    checkState(this.removalListener == null);
976
977    // safely limiting the kinds of caches this can produce
978    @SuppressWarnings("unchecked")
979    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
980    me.removalListener = checkNotNull(listener);
981    return me;
982  }
983
984  // Make a safe contravariant cast now so we don't have to do it over and over.
985  @SuppressWarnings("unchecked")
986  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
987    return (RemovalListener<K1, V1>)
988        MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
989  }
990
991  /**
992   * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
993   * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
994   * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
995   * cache operation.
996   *
997   * @return this {@code CacheBuilder} instance (for chaining)
998   * @since 12.0 (previously, stats collection was automatic)
999   */
1000  @CanIgnoreReturnValue
1001  public CacheBuilder<K, V> recordStats() {
1002    statsCounterSupplier = CACHE_STATS_COUNTER;
1003    return this;
1004  }
1005
1006  boolean isRecordingStats() {
1007    return statsCounterSupplier == CACHE_STATS_COUNTER;
1008  }
1009
1010  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
1011    return statsCounterSupplier;
1012  }
1013
1014  /**
1015   * Builds a cache, which either returns an already-loaded value for a given key or atomically
1016   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
1017   * loading the value for this key, simply waits for that thread to finish and returns its loaded
1018   * value. Note that multiple threads can concurrently load values for distinct keys.
1019   *
1020   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
1021   * invoked again to create multiple independent caches.
1022   *
1023   * @param loader the cache loader used to obtain new values
1024   * @return a cache having the requested features
1025   */
1026  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
1027      CacheLoader<? super K1, V1> loader) {
1028    checkWeightWithWeigher();
1029    return new LocalCache.LocalLoadingCache<>(this, loader);
1030  }
1031
1032  /**
1033   * Builds a cache which does not automatically load values when keys are requested.
1034   *
1035   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
1036   * CacheLoader}.
1037   *
1038   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
1039   * invoked again to create multiple independent caches.
1040   *
1041   * @return a cache having the requested features
1042   * @since 11.0
1043   */
1044  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
1045    checkWeightWithWeigher();
1046    checkNonLoadingCache();
1047    return new LocalCache.LocalManualCache<>(this);
1048  }
1049
1050  private void checkNonLoadingCache() {
1051    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
1052  }
1053
1054  private void checkWeightWithWeigher() {
1055    if (weigher == null) {
1056      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
1057    } else {
1058      if (strictParsing) {
1059        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
1060      } else {
1061        if (maximumWeight == UNSET_INT) {
1062          LoggerHolder.logger.log(
1063              Level.WARNING, "ignoring weigher specified without maximumWeight");
1064        }
1065      }
1066    }
1067  }
1068
1069  /**
1070   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
1071   * string is not specified.
1072   */
1073  @Override
1074  public String toString() {
1075    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
1076    if (initialCapacity != UNSET_INT) {
1077      s.add("initialCapacity", initialCapacity);
1078    }
1079    if (concurrencyLevel != UNSET_INT) {
1080      s.add("concurrencyLevel", concurrencyLevel);
1081    }
1082    if (maximumSize != UNSET_INT) {
1083      s.add("maximumSize", maximumSize);
1084    }
1085    if (maximumWeight != UNSET_INT) {
1086      s.add("maximumWeight", maximumWeight);
1087    }
1088    if (expireAfterWriteNanos != UNSET_INT) {
1089      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
1090    }
1091    if (expireAfterAccessNanos != UNSET_INT) {
1092      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
1093    }
1094    if (keyStrength != null) {
1095      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
1096    }
1097    if (valueStrength != null) {
1098      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
1099    }
1100    if (keyEquivalence != null) {
1101      s.addValue("keyEquivalence");
1102    }
1103    if (valueEquivalence != null) {
1104      s.addValue("valueEquivalence");
1105    }
1106    if (removalListener != null) {
1107      s.addValue("removalListener");
1108    }
1109    return s.toString();
1110  }
1111
1112  /**
1113   * Returns the number of nanoseconds of the given duration without throwing or overflowing.
1114   *
1115   * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either
1116   * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing
1117   * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair.
1118   */
1119  @GwtIncompatible // java.time.Duration
1120  @SuppressWarnings("GoodTime") // duration decomposition
1121  private static long toNanosSaturated(java.time.Duration duration) {
1122    // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for
1123    // durations longer than approximately +/- 292 years).
1124    try {
1125      return duration.toNanos();
1126    } catch (ArithmeticException tooBig) {
1127      return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE;
1128    }
1129  }
1130}