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