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