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