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