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.checkerframework.checker.nullness.qual.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 33.3.0 (but since 25.0 in the JRE <a
721   *     href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>)
722   */
723  @J2ObjCIncompatible
724  @GwtIncompatible // Duration
725  @SuppressWarnings({
726    "GoodTime", // Duration decomposition
727    "Java7ApiChecker",
728  })
729  @IgnoreJRERequirement // No more dangerous than wherever the caller got the Duration from
730  @CanIgnoreReturnValue
731  public CacheBuilder<K, V> expireAfterWrite(Duration duration) {
732    return expireAfterWrite(toNanosSaturated(duration), NANOSECONDS);
733  }
734
735  /**
736   * Specifies that each entry should be automatically removed from the cache once a fixed duration
737   * has elapsed after the entry's creation, or the most recent replacement of its value.
738   *
739   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
740   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
741   * useful in testing, or to disable caching temporarily without a code change.
742   *
743   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
744   * write operations. Expired entries are cleaned up as part of the routine maintenance described
745   * in the class javadoc.
746   *
747   * <p>If you can represent the duration as a {@link Duration} (which should be preferred when
748   * feasible), use {@link #expireAfterWrite(Duration)} instead.
749   *
750   * @param duration the length of time after an entry is created that it should be automatically
751   *     removed
752   * @param unit the unit that {@code duration} is expressed in
753   * @return this {@code CacheBuilder} instance (for chaining)
754   * @throws IllegalArgumentException if {@code duration} is negative
755   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
756   */
757  @SuppressWarnings("GoodTime") // should accept a Duration
758  @CanIgnoreReturnValue
759  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
760    checkState(
761        expireAfterWriteNanos == UNSET_INT,
762        "expireAfterWrite was already set to %s ns",
763        expireAfterWriteNanos);
764    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
765    this.expireAfterWriteNanos = unit.toNanos(duration);
766    return this;
767  }
768
769  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
770  long getExpireAfterWriteNanos() {
771    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
772  }
773
774  /**
775   * Specifies that each entry should be automatically removed from the cache once a fixed duration
776   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
777   * access. Access time is reset by all cache read and write operations (including {@code
778   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
779   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}}. So,
780   * for example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for
781   * the entries you retrieve.
782   *
783   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
784   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
785   * useful in testing, or to disable caching temporarily without a code change.
786   *
787   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
788   * write operations. Expired entries are cleaned up as part of the routine maintenance described
789   * in the class javadoc.
790   *
791   * @param duration the length of time after an entry is last accessed that it should be
792   *     automatically removed
793   * @return this {@code CacheBuilder} instance (for chaining)
794   * @throws IllegalArgumentException if {@code duration} is negative
795   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
796   * @throws ArithmeticException for durations greater than +/- approximately 292 years
797   * @since 33.3.0 (but since 25.0 in the JRE <a
798   *     href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>)
799   */
800  @J2ObjCIncompatible
801  @GwtIncompatible // Duration
802  @SuppressWarnings({
803    "GoodTime", // Duration decomposition
804    "Java7ApiChecker",
805  })
806  @IgnoreJRERequirement // No more dangerous than wherever the caller got the Duration from
807  @CanIgnoreReturnValue
808  public CacheBuilder<K, V> expireAfterAccess(Duration duration) {
809    return expireAfterAccess(toNanosSaturated(duration), NANOSECONDS);
810  }
811
812  /**
813   * Specifies that each entry should be automatically removed from the cache once a fixed duration
814   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
815   * access. Access time is reset by all cache read and write operations (including {@code
816   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
817   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for
818   * example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the
819   * entries you retrieve.
820   *
821   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
822   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
823   * useful in testing, or to disable caching temporarily without a code change.
824   *
825   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
826   * write operations. Expired entries are cleaned up as part of the routine maintenance described
827   * in the class javadoc.
828   *
829   * <p>If you can represent the duration as a {@link Duration} (which should be preferred when
830   * feasible), use {@link #expireAfterAccess(Duration)} instead.
831   *
832   * @param duration the length of time after an entry is last accessed that it should be
833   *     automatically removed
834   * @param unit the unit that {@code duration} is expressed in
835   * @return this {@code CacheBuilder} instance (for chaining)
836   * @throws IllegalArgumentException if {@code duration} is negative
837   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
838   */
839  @SuppressWarnings("GoodTime") // should accept a Duration
840  @CanIgnoreReturnValue
841  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
842    checkState(
843        expireAfterAccessNanos == UNSET_INT,
844        "expireAfterAccess was already set to %s ns",
845        expireAfterAccessNanos);
846    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
847    this.expireAfterAccessNanos = unit.toNanos(duration);
848    return this;
849  }
850
851  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
852  long getExpireAfterAccessNanos() {
853    return (expireAfterAccessNanos == UNSET_INT)
854        ? DEFAULT_EXPIRATION_NANOS
855        : expireAfterAccessNanos;
856  }
857
858  /**
859   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
860   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
861   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
862   * CacheLoader#reload}.
863   *
864   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
865   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
866   * implementation; otherwise refreshes will be performed during unrelated cache read and write
867   * operations.
868   *
869   * <p>Currently automatic refreshes are performed when the first stale request for an entry
870   * occurs. The request triggering refresh will make a synchronous call to {@link
871   * CacheLoader#reload}
872   * to obtain a future of the new value. If the returned future is already complete, it is returned
873   * immediately. Otherwise, the old value is returned.
874   *
875   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
876   *
877   * @param duration the length of time after an entry is created that it should be considered
878   *     stale, and thus eligible for refresh
879   * @return this {@code CacheBuilder} instance (for chaining)
880   * @throws IllegalArgumentException if {@code duration} is negative
881   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
882   * @throws ArithmeticException for durations greater than +/- approximately 292 years
883   * @since 33.3.0 (but since 25.0 in the JRE <a
884   *     href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>)
885   */
886  @J2ObjCIncompatible
887  @GwtIncompatible // Duration
888  @SuppressWarnings({
889    "GoodTime", // Duration decomposition
890    "Java7ApiChecker",
891  })
892  @IgnoreJRERequirement // No more dangerous than wherever the caller got the Duration from
893  @CanIgnoreReturnValue
894  public CacheBuilder<K, V> refreshAfterWrite(Duration duration) {
895    return refreshAfterWrite(toNanosSaturated(duration), NANOSECONDS);
896  }
897
898  /**
899   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
900   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
901   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
902   * CacheLoader#reload}.
903   *
904   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
905   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
906   * implementation; otherwise refreshes will be performed during unrelated cache read and write
907   * operations.
908   *
909   * <p>Currently automatic refreshes are performed when the first stale request for an entry
910   * occurs. The request triggering refresh will make a synchronous call to {@link
911   * CacheLoader#reload}
912   * and immediately return the new value if the returned future is complete, and the old value
913   * otherwise.
914   *
915   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
916   *
917   * <p>If you can represent the duration as a {@link Duration} (which should be preferred when
918   * feasible), use {@link #refreshAfterWrite(Duration)} instead.
919   *
920   * @param duration the length of time after an entry is created that it should be considered
921   *     stale, and thus eligible for refresh
922   * @param unit the unit that {@code duration} is expressed in
923   * @return this {@code CacheBuilder} instance (for chaining)
924   * @throws IllegalArgumentException if {@code duration} is negative
925   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
926   * @since 11.0
927   */
928  @GwtIncompatible // To be supported (synchronously).
929  @SuppressWarnings("GoodTime") // should accept a Duration
930  @CanIgnoreReturnValue
931  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
932    checkNotNull(unit);
933    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
934    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
935    this.refreshNanos = unit.toNanos(duration);
936    return this;
937  }
938
939  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
940  long getRefreshNanos() {
941    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
942  }
943
944  /**
945   * Specifies a nanosecond-precision time source for this cache. By default, {@link
946   * System#nanoTime} is used.
947   *
948   * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
949   * time source.
950   *
951   * @return this {@code CacheBuilder} instance (for chaining)
952   * @throws IllegalStateException if a ticker was already set
953   */
954  @CanIgnoreReturnValue
955  public CacheBuilder<K, V> ticker(Ticker ticker) {
956    checkState(this.ticker == null);
957    this.ticker = checkNotNull(ticker);
958    return this;
959  }
960
961  Ticker getTicker(boolean recordsTime) {
962    if (ticker != null) {
963      return ticker;
964    }
965    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
966  }
967
968  /**
969   * Specifies a listener instance that caches should notify each time an entry is removed for any
970   * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
971   * as part of the routine maintenance described in the class documentation above.
972   *
973   * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
974   * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
975   * same instance, but only the returned reference has the correct generic type information to
976   * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the
977   * class documentation above, configuring a builder and building your cache in a single statement.
978   * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache
979   * operation at some <i>undefined</i> point in the future.
980   *
981   * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
982   * the {@code Cache} user, only logged via a {@link Logger}.
983   *
984   * @return the cache builder reference that should be used instead of {@code this} for any
985   *     remaining configuration and cache building
986   * @throws IllegalStateException if a removal listener was already set
987   */
988  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
989      RemovalListener<? super K1, ? super V1> listener) {
990    checkState(this.removalListener == null);
991
992    // safely limiting the kinds of caches this can produce
993    @SuppressWarnings("unchecked")
994    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
995    me.removalListener = checkNotNull(listener);
996    return me;
997  }
998
999  // Make a safe contravariant cast now so we don't have to do it over and over.
1000  @SuppressWarnings("unchecked")
1001  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
1002    return (RemovalListener<K1, V1>)
1003        MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
1004  }
1005
1006  /**
1007   * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
1008   * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
1009   * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
1010   * cache operation.
1011   *
1012   * @return this {@code CacheBuilder} instance (for chaining)
1013   * @since 12.0 (previously, stats collection was automatic)
1014   */
1015  @CanIgnoreReturnValue
1016  public CacheBuilder<K, V> recordStats() {
1017    statsCounterSupplier = CACHE_STATS_COUNTER;
1018    return this;
1019  }
1020
1021  boolean isRecordingStats() {
1022    return statsCounterSupplier == CACHE_STATS_COUNTER;
1023  }
1024
1025  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
1026    return statsCounterSupplier;
1027  }
1028
1029  /**
1030   * Builds a cache, which either returns an already-loaded value for a given key or atomically
1031   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
1032   * loading the value for this key, simply waits for that thread to finish and returns its loaded
1033   * value. Note that multiple threads can concurrently load values for distinct keys.
1034   *
1035   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
1036   * invoked again to create multiple independent caches.
1037   *
1038   * @param loader the cache loader used to obtain new values
1039   * @return a cache having the requested features
1040   */
1041  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
1042      CacheLoader<? super K1, V1> loader) {
1043    checkWeightWithWeigher();
1044    return new LocalCache.LocalLoadingCache<>(this, loader);
1045  }
1046
1047  /**
1048   * Builds a cache which does not automatically load values when keys are requested.
1049   *
1050   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
1051   * CacheLoader}.
1052   *
1053   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
1054   * invoked again to create multiple independent caches.
1055   *
1056   * @return a cache having the requested features
1057   * @since 11.0
1058   */
1059  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
1060    checkWeightWithWeigher();
1061    checkNonLoadingCache();
1062    return new LocalCache.LocalManualCache<>(this);
1063  }
1064
1065  private void checkNonLoadingCache() {
1066    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
1067  }
1068
1069  private void checkWeightWithWeigher() {
1070    if (weigher == null) {
1071      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
1072    } else {
1073      if (strictParsing) {
1074        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
1075      } else {
1076        if (maximumWeight == UNSET_INT) {
1077          LoggerHolder.logger.log(
1078              Level.WARNING, "ignoring weigher specified without maximumWeight");
1079        }
1080      }
1081    }
1082  }
1083
1084  /**
1085   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
1086   * string is not specified.
1087   */
1088  @Override
1089  public String toString() {
1090    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
1091    if (initialCapacity != UNSET_INT) {
1092      s.add("initialCapacity", initialCapacity);
1093    }
1094    if (concurrencyLevel != UNSET_INT) {
1095      s.add("concurrencyLevel", concurrencyLevel);
1096    }
1097    if (maximumSize != UNSET_INT) {
1098      s.add("maximumSize", maximumSize);
1099    }
1100    if (maximumWeight != UNSET_INT) {
1101      s.add("maximumWeight", maximumWeight);
1102    }
1103    if (expireAfterWriteNanos != UNSET_INT) {
1104      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
1105    }
1106    if (expireAfterAccessNanos != UNSET_INT) {
1107      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
1108    }
1109    if (keyStrength != null) {
1110      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
1111    }
1112    if (valueStrength != null) {
1113      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
1114    }
1115    if (keyEquivalence != null) {
1116      s.addValue("keyEquivalence");
1117    }
1118    if (valueEquivalence != null) {
1119      s.addValue("valueEquivalence");
1120    }
1121    if (removalListener != null) {
1122      s.addValue("removalListener");
1123    }
1124    return s.toString();
1125  }
1126
1127  /**
1128   * Returns the number of nanoseconds of the given duration without throwing or overflowing.
1129   *
1130   * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either
1131   * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing
1132   * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair.
1133   */
1134  @GwtIncompatible // Duration
1135  @SuppressWarnings({
1136    "GoodTime", // Duration decomposition
1137    "Java7ApiChecker",
1138  })
1139  @IgnoreJRERequirement // No more dangerous than wherever the caller got the Duration from
1140  private static long toNanosSaturated(Duration duration) {
1141    // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for
1142    // durations longer than approximately +/- 292 years).
1143    try {
1144      return duration.toNanos();
1145    } catch (ArithmeticException tooBig) {
1146      return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE;
1147    }
1148  }
1149}