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