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