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