001 /* 002 * Copyright (C) 2009 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017 package com.google.common.cache; 018 019 import static com.google.common.base.Objects.firstNonNull; 020 import static com.google.common.base.Preconditions.checkArgument; 021 import static com.google.common.base.Preconditions.checkNotNull; 022 import static com.google.common.base.Preconditions.checkState; 023 024 import com.google.common.annotations.Beta; 025 import com.google.common.base.Ascii; 026 import com.google.common.base.Equivalence; 027 import com.google.common.base.Equivalences; 028 import com.google.common.base.Objects; 029 import com.google.common.base.Supplier; 030 import com.google.common.base.Suppliers; 031 import com.google.common.base.Ticker; 032 import com.google.common.cache.AbstractCache.SimpleStatsCounter; 033 import com.google.common.cache.AbstractCache.StatsCounter; 034 import com.google.common.cache.CustomConcurrentHashMap.Strength; 035 import com.google.common.collect.ForwardingConcurrentMap; 036 import com.google.common.collect.ImmutableList; 037 import com.google.common.util.concurrent.ExecutionError; 038 import com.google.common.util.concurrent.UncheckedExecutionException; 039 040 import java.io.Serializable; 041 import java.lang.ref.SoftReference; 042 import java.lang.ref.WeakReference; 043 import java.util.AbstractMap; 044 import java.util.Collections; 045 import java.util.ConcurrentModificationException; 046 import java.util.Map; 047 import java.util.Set; 048 import java.util.concurrent.ConcurrentHashMap; 049 import java.util.concurrent.ConcurrentMap; 050 import java.util.concurrent.ExecutionException; 051 import java.util.concurrent.TimeUnit; 052 053 import javax.annotation.CheckReturnValue; 054 import javax.annotation.Nullable; 055 056 /** 057 * <p>A builder of {@link Cache} instances having any combination of the following features: 058 * 059 * <ul> 060 * <li>least-recently-used eviction when a maximum size is exceeded 061 * <li>time-based expiration of entries, measured since last access or last write 062 * <li>keys automatically wrapped in {@linkplain WeakReference weak} references 063 * <li>values automatically wrapped in {@linkplain WeakReference weak} or 064 * {@linkplain SoftReference soft} references 065 * <li>notification of evicted (or otherwise removed) entries 066 * </ul> 067 * 068 * <p>Usage example: <pre> {@code 069 * 070 * Cache<Key, Graph> graphs = CacheBuilder.newBuilder() 071 * .concurrencyLevel(4) 072 * .weakKeys() 073 * .maximumSize(10000) 074 * .expireAfterWrite(10, TimeUnit.MINUTES) 075 * .build( 076 * new CacheLoader<Key, Graph>() { 077 * public Graph load(Key key) throws AnyException { 078 * return createExpensiveGraph(key); 079 * } 080 * });}</pre> 081 * 082 * 083 * These features are all optional. 084 * 085 * <p>The returned cache is implemented as a hash table with similar performance characteristics to 086 * {@link ConcurrentHashMap}. It implements the optional operations {@link Cache#invalidate}, 087 * {@link Cache#invalidateAll}, {@link Cache#size}, {@link Cache#stats}, and {@link Cache#asMap}, 088 * with the following qualifications: 089 * 090 * <ul> 091 * <li>The {@code invalidateAll} method will invalidate all cached entries prior to returning, and 092 * removal notifications will be issued for all invalidated entries. 093 * <li>The {@code asMap} view supports removal operations, but no other modifications. 094 * <li>The {@code asMap} view (and its collection views) have <i>weakly consistent iterators</i>. 095 * This means that they are safe for concurrent use, but if other threads modify the cache after 096 * the iterator is created, it is undefined which of these changes, if any, are reflected in 097 * that iterator. These iterators never throw {@link ConcurrentModificationException}. 098 * </ul> 099 * 100 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the 101 * {@link Object#equals equals} method) to determine equality for keys or values. However, if 102 * {@link #weakKeys} was specified, the cache uses identity ({@code ==}) 103 * comparisons instead for keys. Likewise, if {@link #weakValues} or {@link #softValues} was 104 * specified, the cache uses identity comparisons for values. 105 * 106 * <p>If soft or weak references were requested, it is possible for a key or value present in the 107 * the cache to be reclaimed by the garbage collector. If this happens, the entry automatically 108 * disappears from the cache. A partially-reclaimed entry is never exposed to the user. 109 * 110 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which 111 * will be performed during write operations, or during occasional read operations in the absense of 112 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but 113 * calling it should not be necessary with a high throughput cache. Only caches built with 114 * {@linkplain CacheBuilder#removalListener removalListener}, 115 * {@linkplain CacheBuilder#expireAfterWrite expireAfterWrite}, 116 * {@linkplain CacheBuilder#expireAfterAccess expireAfterAccess}, 117 * {@linkplain CacheBuilder#weakKeys weakKeys}, {@linkplain CacheBuilder#weakValues weakValues}, 118 * or {@linkplain CacheBuilder#softValues softValues} perform periodic maintenance. 119 * 120 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches 121 * retain all the configuration properties of the original cache. Note that the serialized form does 122 * <i>not</i> include cache contents, but only configuration. 123 * 124 * @param <K> the base key type for all caches created by this builder 125 * @param <V> the base value type for all caches created by this builder 126 * @author Charles Fry 127 * @author Kevin Bourrillion 128 * @since 10.0 129 */ 130 @Beta 131 public final class CacheBuilder<K, V> { 132 private static final int DEFAULT_INITIAL_CAPACITY = 16; 133 private static final int DEFAULT_CONCURRENCY_LEVEL = 4; 134 private static final int DEFAULT_EXPIRATION_NANOS = 0; 135 136 static final Supplier<? extends StatsCounter> DEFAULT_STATS_COUNTER = Suppliers.ofInstance( 137 new StatsCounter() { 138 @Override 139 public void recordHit() {} 140 141 @Override 142 public void recordLoadSuccess(long loadTime) {} 143 144 @Override 145 public void recordLoadException(long loadTime) {} 146 147 @Override 148 public void recordConcurrentMiss() {} 149 150 @Override 151 public void recordEviction() {} 152 153 @Override 154 public CacheStats snapshot() { 155 return EMPTY_STATS; 156 } 157 }); 158 static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0); 159 160 static final Supplier<SimpleStatsCounter> CACHE_STATS_COUNTER = 161 new Supplier<SimpleStatsCounter>() { 162 @Override 163 public SimpleStatsCounter get() { 164 return new SimpleStatsCounter(); 165 } 166 }; 167 168 enum NullListener implements RemovalListener<Object, Object> { 169 INSTANCE; 170 171 @Override 172 public void onRemoval(RemovalNotification<Object, Object> notification) {} 173 } 174 175 static final int UNSET_INT = -1; 176 177 int initialCapacity = UNSET_INT; 178 int concurrencyLevel = UNSET_INT; 179 int maximumSize = UNSET_INT; 180 181 Strength keyStrength; 182 Strength valueStrength; 183 184 long expireAfterWriteNanos = UNSET_INT; 185 long expireAfterAccessNanos = UNSET_INT; 186 187 RemovalCause nullRemovalCause; 188 189 Equivalence<Object> keyEquivalence; 190 Equivalence<Object> valueEquivalence; 191 192 RemovalListener<? super K, ? super V> removalListener; 193 194 Ticker ticker; 195 196 // TODO(fry): make constructor private and update tests to use newBuilder 197 CacheBuilder() {} 198 199 /** 200 * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys, 201 * strong values, and no automatic eviction of any kind. 202 */ 203 public static CacheBuilder<Object, Object> newBuilder() { 204 return new CacheBuilder<Object, Object>(); 205 } 206 207 private boolean useNullCache() { 208 return (nullRemovalCause == null); 209 } 210 211 /** 212 * Sets a custom {@code Equivalence} strategy for comparing keys. 213 * 214 * <p>By default, the cache uses {@link Equivalences#identity} to determine key equality when 215 * {@link #weakKeys} is specified, and {@link Equivalences#equals()} otherwise. 216 */ 217 CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) { 218 checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); 219 keyEquivalence = checkNotNull(equivalence); 220 return this; 221 } 222 223 Equivalence<Object> getKeyEquivalence() { 224 return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence()); 225 } 226 227 /** 228 * Sets a custom {@code Equivalence} strategy for comparing values. 229 * 230 * <p>By default, the cache uses {@link Equivalences#identity} to determine value equality when 231 * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalences#equals()} 232 * otherwise. 233 */ 234 CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) { 235 checkState(valueEquivalence == null, 236 "value equivalence was already set to %s", valueEquivalence); 237 this.valueEquivalence = checkNotNull(equivalence); 238 return this; 239 } 240 241 Equivalence<Object> getValueEquivalence() { 242 return firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence()); 243 } 244 245 /** 246 * Sets the minimum total size for the internal hash tables. For example, if the initial capacity 247 * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each 248 * having a hash table of size eight. Providing a large enough estimate at construction time 249 * avoids the need for expensive resizing operations later, but setting this value unnecessarily 250 * high wastes memory. 251 * 252 * @throws IllegalArgumentException if {@code initialCapacity} is negative 253 * @throws IllegalStateException if an initial capacity was already set 254 */ 255 public CacheBuilder<K, V> initialCapacity(int initialCapacity) { 256 checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s", 257 this.initialCapacity); 258 checkArgument(initialCapacity >= 0); 259 this.initialCapacity = initialCapacity; 260 return this; 261 } 262 263 int getInitialCapacity() { 264 return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity; 265 } 266 267 /** 268 * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The 269 * table is internally partitioned to try to permit the indicated number of concurrent updates 270 * without contention. Because assignment of entries to these partitions is not necessarily 271 * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to 272 * accommodate as many threads as will ever concurrently modify the table. Using a significantly 273 * higher value than you need can waste space and time, and a significantly lower value can lead 274 * to thread contention. But overestimates and underestimates within an order of magnitude do not 275 * usually have much noticeable impact. A value of one permits only one thread to modify the cache 276 * at a time, but since read operations can proceed concurrently, this still yields higher 277 * concurrency than full synchronization. Defaults to 4. 278 * 279 * <p><b>Note:</b>The default may change in the future. If you care about this value, you should 280 * always choose it explicitly. 281 * 282 * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive 283 * @throws IllegalStateException if a concurrency level was already set 284 */ 285 public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) { 286 checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", 287 this.concurrencyLevel); 288 checkArgument(concurrencyLevel > 0); 289 this.concurrencyLevel = concurrencyLevel; 290 return this; 291 } 292 293 int getConcurrencyLevel() { 294 return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; 295 } 296 297 /** 298 * Specifies the maximum number of entries the cache may contain. Note that the cache <b>may evict 299 * an entry before this limit is exceeded</b>. As the cache size grows close to the maximum, the 300 * cache evicts entries that are less likely to be used again. For example, the cache may evict an 301 * entry because it hasn't been used recently or very often. 302 * 303 * <p>When {@code size} is zero, elements will be evicted immediately after being loaded into the 304 * cache. This has the same effect as invoking {@link #expireAfterWrite 305 * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0, 306 * unit)}. It can be useful in testing, or to disable caching temporarily without a code change. 307 * 308 * @param size the maximum size of the cache 309 * @throws IllegalArgumentException if {@code size} is negative 310 * @throws IllegalStateException if a maximum size was already set 311 */ 312 public CacheBuilder<K, V> maximumSize(int size) { 313 checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s", 314 this.maximumSize); 315 checkArgument(size >= 0, "maximum size must not be negative"); 316 this.maximumSize = size; 317 if (maximumSize == 0) { 318 // SIZE trumps EXPIRED 319 this.nullRemovalCause = RemovalCause.SIZE; 320 } 321 return this; 322 } 323 324 /** 325 * Specifies that each key (not value) stored in the cache should be strongly referenced. 326 * 327 * @throws IllegalStateException if the key strength was already set 328 */ 329 CacheBuilder<K, V> strongKeys() { 330 return setKeyStrength(Strength.STRONG); 331 } 332 333 /** 334 * Specifies that each key (not value) stored in the cache should be wrapped in a {@link 335 * WeakReference} (by default, strong references are used). 336 * 337 * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==}) 338 * comparison to determine equality of keys. 339 * 340 * <p>Entries with keys that have been garbage collected may be counted by {@link Cache#size}, but 341 * will never be visible to read or write operations. Entries with garbage collected keys are 342 * cleaned up as part of the routine maintenance described in the class javadoc. 343 * 344 * @throws IllegalStateException if the key strength was already set 345 */ 346 public CacheBuilder<K, V> weakKeys() { 347 return setKeyStrength(Strength.WEAK); 348 } 349 350 CacheBuilder<K, V> setKeyStrength(Strength strength) { 351 checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); 352 keyStrength = checkNotNull(strength); 353 return this; 354 } 355 356 Strength getKeyStrength() { 357 return firstNonNull(keyStrength, Strength.STRONG); 358 } 359 360 /** 361 * Specifies that each value (not key) stored in the cache should be strongly referenced. 362 * 363 * @throws IllegalStateException if the value strength was already set 364 */ 365 CacheBuilder<K, V> strongValues() { 366 return setValueStrength(Strength.STRONG); 367 } 368 369 /** 370 * Specifies that each value (not key) stored in the cache should be wrapped in a 371 * {@link WeakReference} (by default, strong references are used). 372 * 373 * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor 374 * candidate for caching; consider {@link #softValues} instead. 375 * 376 * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==}) 377 * comparison to determine equality of values. 378 * 379 * <p>Entries with values that have been garbage collected may be counted by {@link Cache#size}, 380 * but will never be visible to read or write operations. Entries with garbage collected keys are 381 * cleaned up as part of the routine maintenance described in the class javadoc. 382 * 383 * @throws IllegalStateException if the value strength was already set 384 */ 385 public CacheBuilder<K, V> weakValues() { 386 return setValueStrength(Strength.WEAK); 387 } 388 389 /** 390 * Specifies that each value (not key) stored in the cache should be wrapped in a 391 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will 392 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory 393 * demand. 394 * 395 * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain 396 * #maximumSize maximum size} instead of using soft references. You should only use this method if 397 * you are well familiar with the practical consequences of soft references. 398 * 399 * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==}) 400 * comparison to determine equality of values. 401 * 402 * <p>Entries with values that have been garbage collected may be counted by {@link Cache#size}, 403 * but will never be visible to read or write operations. Entries with garbage collected values 404 * are cleaned up as part of the routine maintenance described in the class javadoc. 405 * 406 * @throws IllegalStateException if the value strength was already set 407 */ 408 public CacheBuilder<K, V> softValues() { 409 return setValueStrength(Strength.SOFT); 410 } 411 412 CacheBuilder<K, V> setValueStrength(Strength strength) { 413 checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); 414 valueStrength = checkNotNull(strength); 415 return this; 416 } 417 418 Strength getValueStrength() { 419 return firstNonNull(valueStrength, Strength.STRONG); 420 } 421 422 /** 423 * Specifies that each entry should be automatically removed from the cache once a fixed duration 424 * has elapsed after the entry's creation, or the most recent replacement of its value. 425 * 426 * <p>When {@code duration} is zero, elements will be evicted immediately after being loaded into 427 * the cache. This has the same effect as invoking {@link #maximumSize maximumSize}{@code (0)}. It 428 * can be useful in testing, or to disable caching temporarily without a code change. 429 * 430 * <p>Expired entries may be counted by {@link Cache#size}, but will never be visible to read or 431 * write operations. Expired entries are cleaned up as part of the routine maintenance described 432 * in the class javadoc. 433 * 434 * @param duration the length of time after an entry is created that it should be automatically 435 * removed 436 * @param unit the unit that {@code duration} is expressed in 437 * @throws IllegalArgumentException if {@code duration} is negative 438 * @throws IllegalStateException if the time to live or time to idle was already set 439 */ 440 public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) { 441 checkExpiration(duration, unit); 442 this.expireAfterWriteNanos = unit.toNanos(duration); 443 if (duration == 0 && this.nullRemovalCause == null) { 444 // SIZE trumps EXPIRED 445 this.nullRemovalCause = RemovalCause.EXPIRED; 446 } 447 return this; 448 } 449 450 private void checkExpiration(long duration, TimeUnit unit) { 451 checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", 452 expireAfterWriteNanos); 453 checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", 454 expireAfterAccessNanos); 455 checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); 456 } 457 458 long getExpireAfterWriteNanos() { 459 return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; 460 } 461 462 /** 463 * Specifies that each entry should be automatically removed from the cache once a fixed duration 464 * has elapsed after the entry's creation, or last access. Access time is reset by 465 * {@link Cache#get} and {@link Cache#getUnchecked}, but not by operations on the view returned by 466 * {@link Cache#asMap}. 467 * 468 * <p>When {@code duration} is zero, elements will be evicted immediately after being loaded into 469 * the cache. This has the same effect as invoking {@link #maximumSize maximumSize}{@code (0)}. It 470 * can be useful in testing, or to disable caching temporarily without a code change. 471 * 472 * <p>Expired entries may be counted by {@link Cache#size}, but will never be visible to read or 473 * write operations. Expired entries are cleaned up as part of the routine maintenance described 474 * in the class javadoc. 475 * 476 * @param duration the length of time after an entry is last accessed that it should be 477 * automatically removed 478 * @param unit the unit that {@code duration} is expressed in 479 * @throws IllegalArgumentException if {@code duration} is negative 480 * @throws IllegalStateException if the time to idle or time to live was already set 481 */ 482 public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) { 483 checkExpiration(duration, unit); 484 this.expireAfterAccessNanos = unit.toNanos(duration); 485 if (duration == 0 && this.nullRemovalCause == null) { 486 // SIZE trumps EXPIRED 487 this.nullRemovalCause = RemovalCause.EXPIRED; 488 } 489 return this; 490 } 491 492 long getExpireAfterAccessNanos() { 493 return (expireAfterAccessNanos == UNSET_INT) 494 ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; 495 } 496 497 /** 498 * Specifies a nanosecond-precision time source for use in determining when entries should be 499 * expired. By default, {@link System#nanoTime} is used. 500 * 501 * <p>The primary intent of this method is to facilitate testing of caches which have been 502 * configured with {@link #expireAfterWrite} or {@link #expireAfterAccess}. 503 * 504 * @throws IllegalStateException if a ticker was already set 505 */ 506 public CacheBuilder<K, V> ticker(Ticker ticker) { 507 checkState(this.ticker == null); 508 this.ticker = checkNotNull(ticker); 509 return this; 510 } 511 512 Ticker getTicker() { 513 return firstNonNull(ticker, Ticker.systemTicker()); 514 } 515 516 /** 517 * Specifies a listener instance, which all caches built using this {@code CacheBuilder} will 518 * notify each time an entry is removed from the cache by any means. 519 * 520 * <p>Each cache built by this {@code CacheBuilder} after this method is called invokes the 521 * supplied listener after removing an element for any reason (see removal causes in {@link 522 * RemovalCause}). It will invoke the listener as part of the routine maintenance described 523 * in the class javadoc. 524 * 525 * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder} 526 * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the 527 * original reference or the returned reference may be used to complete configuration and build 528 * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from 529 * building caches whose key or value types are incompatible with the types accepted by the 530 * listener already provided; the {@code CacheBuilder} type cannot do this. For best results, 531 * simply use the standard method-chaining idiom, as illustrated in the documentation at top, 532 * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement. 533 * 534 * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build 535 * a cache whose key or value type is incompatible with the listener, you will likely experience 536 * a {@link ClassCastException} at some <i>undefined</i> point in the future. 537 * 538 * @throws IllegalStateException if a removal listener was already set 539 */ 540 @CheckReturnValue 541 public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener( 542 RemovalListener<? super K1, ? super V1> listener) { 543 checkState(this.removalListener == null); 544 545 // safely limiting the kinds of caches this can produce 546 @SuppressWarnings("unchecked") 547 CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this; 548 me.removalListener = checkNotNull(listener); 549 return me; 550 } 551 552 // Make a safe contravariant cast now so we don't have to do it over and over. 553 @SuppressWarnings("unchecked") 554 <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() { 555 return (RemovalListener<K1, V1>) Objects.firstNonNull(removalListener, NullListener.INSTANCE); 556 } 557 558 /** 559 * Builds a cache, which either returns an already-loaded value for a given key or atomically 560 * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently 561 * loading the value for this key, simply waits for that thread to finish and returns its 562 * loaded value. Note that multiple threads can concurrently load values for distinct keys. 563 * 564 * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be 565 * invoked again to create multiple independent caches. 566 * 567 * @param loader the cache loader used to obtain new values 568 * @return a cache having the requested features 569 */ 570 public <K1 extends K, V1 extends V> Cache<K1, V1> build(CacheLoader<? super K1, V1> loader) { 571 return useNullCache() 572 ? new ComputingCache<K1, V1>(this, CACHE_STATS_COUNTER, loader) 573 : new NullCache<K1, V1>(this, CACHE_STATS_COUNTER, loader); 574 } 575 576 /** 577 * Returns a string representation for this CacheBuilder instance. The exact form of the returned 578 * string is not specificed. 579 */ 580 @Override 581 public String toString() { 582 Objects.ToStringHelper s = Objects.toStringHelper(this); 583 if (initialCapacity != UNSET_INT) { 584 s.add("initialCapacity", initialCapacity); 585 } 586 if (concurrencyLevel != UNSET_INT) { 587 s.add("concurrencyLevel", concurrencyLevel); 588 } 589 if (maximumSize != UNSET_INT) { 590 s.add("maximumSize", maximumSize); 591 } 592 if (expireAfterWriteNanos != UNSET_INT) { 593 s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); 594 } 595 if (expireAfterAccessNanos != UNSET_INT) { 596 s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); 597 } 598 if (keyStrength != null) { 599 s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); 600 } 601 if (valueStrength != null) { 602 s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); 603 } 604 if (keyEquivalence != null) { 605 s.addValue("keyEquivalence"); 606 } 607 if (valueEquivalence != null) { 608 s.addValue("valueEquivalence"); 609 } 610 if (removalListener != null) { 611 s.addValue("removalListener"); 612 } 613 return s.toString(); 614 } 615 616 /** A map that is always empty and evicts on insertion. */ 617 static class NullConcurrentMap<K, V> extends AbstractMap<K, V> 618 implements ConcurrentMap<K, V>, Serializable { 619 private static final long serialVersionUID = 0; 620 621 private final RemovalListener<K, V> removalListener; 622 private final RemovalCause removalCause; 623 624 NullConcurrentMap(CacheBuilder<? super K, ? super V> builder) { 625 removalListener = builder.getRemovalListener(); 626 removalCause = builder.nullRemovalCause; 627 } 628 629 // implements ConcurrentMap 630 631 @Override 632 public boolean containsKey(@Nullable Object key) { 633 return false; 634 } 635 636 @Override 637 public boolean containsValue(@Nullable Object value) { 638 return false; 639 } 640 641 @Override 642 public V get(@Nullable Object key) { 643 return null; 644 } 645 646 void notifyRemoval(K key, V value) { 647 RemovalNotification<K, V> notification = 648 new RemovalNotification<K, V>(key, value, removalCause); 649 removalListener.onRemoval(notification); 650 } 651 652 @Override 653 public V put(K key, V value) { 654 checkNotNull(key); 655 checkNotNull(value); 656 notifyRemoval(key, value); 657 return null; 658 } 659 660 @Override 661 public V putIfAbsent(K key, V value) { 662 return put(key, value); 663 } 664 665 @Override 666 public V remove(@Nullable Object key) { 667 return null; 668 } 669 670 @Override 671 public boolean remove(@Nullable Object key, @Nullable Object value) { 672 return false; 673 } 674 675 @Override 676 public V replace(K key, V value) { 677 checkNotNull(key); 678 checkNotNull(value); 679 return null; 680 } 681 682 @Override 683 public boolean replace(K key, @Nullable V oldValue, V newValue) { 684 checkNotNull(key); 685 checkNotNull(newValue); 686 return false; 687 } 688 689 @Override 690 public Set<Entry<K, V>> entrySet() { 691 return Collections.emptySet(); 692 } 693 } 694 695 // TODO(fry): remove, as no code path can hit this 696 /** Computes on retrieval and evicts the result. */ 697 static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> { 698 private static final long serialVersionUID = 0; 699 700 final CacheLoader<? super K, ? extends V> loader; 701 702 NullComputingConcurrentMap(CacheBuilder<? super K, ? super V> builder, 703 CacheLoader<? super K, ? extends V> loader) { 704 super(builder); 705 this.loader = checkNotNull(loader); 706 } 707 708 @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred 709 @Override 710 public V get(Object k) { 711 K key = (K) k; 712 V value = compute(key); 713 checkNotNull(value, loader + " returned null for key " + key + "."); 714 notifyRemoval(key, value); 715 return value; 716 } 717 718 private V compute(K key) { 719 checkNotNull(key); 720 try { 721 return loader.load(key); 722 } catch (Exception e) { 723 throw new UncheckedExecutionException(e); 724 } catch (Error e) { 725 throw new ExecutionError(e); 726 } 727 } 728 } 729 730 /** Computes on retrieval and evicts the result. */ 731 static final class NullCache<K, V> extends AbstractCache<K, V> { 732 final NullConcurrentMap<K, V> map; 733 final CacheLoader<? super K, V> loader; 734 735 final StatsCounter statsCounter; 736 737 NullCache(CacheBuilder<? super K, ? super V> builder, 738 Supplier<? extends StatsCounter> statsCounterSupplier, 739 CacheLoader<? super K, V> loader) { 740 this.map = new NullConcurrentMap<K, V>(builder); 741 this.statsCounter = statsCounterSupplier.get(); 742 this.loader = checkNotNull(loader); 743 } 744 745 @Override 746 public V get(K key) throws ExecutionException { 747 V value = compute(key); 748 map.notifyRemoval(key, value); 749 return value; 750 } 751 752 private V compute(K key) throws ExecutionException { 753 checkNotNull(key); 754 long start = System.nanoTime(); 755 V value = null; 756 try { 757 value = loader.load(key); 758 } catch (RuntimeException e) { 759 throw new UncheckedExecutionException(e); 760 } catch (Exception e) { 761 throw new ExecutionException(e); 762 } catch (Error e) { 763 throw new ExecutionError(e); 764 } finally { 765 long elapsed = System.nanoTime() - start; 766 if (value == null) { 767 statsCounter.recordLoadException(elapsed); 768 } else { 769 statsCounter.recordLoadSuccess(elapsed); 770 } 771 statsCounter.recordEviction(); 772 } 773 if (value == null) { 774 throw new NullPointerException(); 775 } else { 776 return value; 777 } 778 } 779 780 @Override 781 public int size() { 782 return 0; 783 } 784 785 @Override 786 public void invalidate(Object key) { 787 // no-op 788 } 789 790 @Override public void invalidateAll() { 791 // no-op 792 } 793 794 @Override 795 public CacheStats stats() { 796 return statsCounter.snapshot(); 797 } 798 799 @Override 800 public ImmutableList<Map.Entry<K, V>> activeEntries(int limit) { 801 return ImmutableList.of(); 802 } 803 804 ConcurrentMap<K, V> asMap; 805 806 @Override 807 public ConcurrentMap<K, V> asMap() { 808 ConcurrentMap<K, V> am = asMap; 809 return (am != null) ? am : (asMap = new CacheAsMap<K, V>(map)); 810 } 811 } 812 813 static final class CacheAsMap<K, V> extends ForwardingConcurrentMap<K, V> { 814 private final ConcurrentMap<K, V> delegate; 815 816 CacheAsMap(ConcurrentMap<K, V> delegate) { 817 this.delegate = delegate; 818 } 819 820 @Override 821 protected ConcurrentMap<K, V> delegate() { 822 return delegate; 823 } 824 825 @Override 826 public V put(K key, V value) { 827 throw new UnsupportedOperationException(); 828 } 829 830 @Override 831 public void putAll(Map<? extends K, ? extends V> map) { 832 throw new UnsupportedOperationException(); 833 } 834 835 @Override 836 public V putIfAbsent(K key, V value) { 837 throw new UnsupportedOperationException(); 838 } 839 840 @Override 841 public V replace(K key, V value) { 842 throw new UnsupportedOperationException(); 843 } 844 845 @Override 846 public boolean replace(K key, V oldValue, V newValue) { 847 throw new UnsupportedOperationException(); 848 } 849 } 850 851 }