Class SafeCacheBuilder<K,V>
-
Method Summary
Modifier and TypeMethodDescription<K1 extends K,V1 extends V>
ConcurrentMap<K1, V1> build(com.google.common.cache.CacheLoader<? super K1, V1> loader) Returns the cache wrapped as a ConcurrentMap.concurrencyLevel(int concurrencyLevel) Guides the allowed concurrency among update operations.expireAfterAccess(long duration, TimeUnit unit) Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or last access.expireAfterWrite(long duration, TimeUnit unit) Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.initialCapacity(int initialCapacity) Sets the minimum total size for the internal hash tables.maximumSize(int size) Specifies the maximum number of entries the cache may contain.static <K,V> SafeCacheBuilder <K, V> Construct a new safe cache builder.<K1 extends K,V1 extends V>
SafeCacheBuilder<K1, V1> removalListener(com.google.common.cache.RemovalListener<? super K1, ? super V1> listener) Specifies a listener instance, which all caches built using thisCacheBuilderwill notify each time an entry is removed from the cache by any means.Specifies that each value (not key) stored in the cache should be wrapped in aSoftReference(by default, strong references are used).ticker(com.google.common.base.Ticker ticker) Specifies a nanosecond-precision time source for use in determining when entries should be expired.weakKeys()Specifies that each key (not value) stored in the cache should be wrapped in aWeakReference(by default, strong references are used).Specifies that each value (not key) stored in the cache should be wrapped in aWeakReference(by default, strong references are used).
-
Method Details
-
newBuilder
Construct a new safe cache builder.- Type Parameters:
K- Key typeV- Value type- Returns:
- A new cache builder.
-
concurrencyLevel
Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. Because assignment of entries to these partitions is not necessarily uniform, the actual concurrency observed may vary. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention. But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact. A value of one permits only one thread to modify the cache at a time, but since read operations can proceed concurrently, this still yields higher concurrency than full synchronization. Defaults to 4.Note:The default may change in the future. If you care about this value, you should always choose it explicitly.
- Parameters:
concurrencyLevel- New concurrency level- Returns:
- This for chaining
- Throws:
IllegalArgumentException- ifconcurrencyLevelis nonpositiveIllegalStateException- if a concurrency level was already set
-
expireAfterAccess
Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or last access. Access time is reset byCache.get(), but not by operations on the view returned byCache.asMap().When
durationis zero, elements will be evicted immediately after being loaded into the cache. This has the same effect as invokingmaximumSize(0). It can be useful in testing, or to disable caching temporarily without a code change.Expired entries may be counted by
Cache.size(), but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future.- Parameters:
duration- the length of time after an entry is last accessed that it should be automatically removedunit- the unit thatdurationis expressed in- Returns:
- This for chaining
- Throws:
IllegalArgumentException- ifdurationis negativeIllegalStateException- if the time to idle or time to live was already set
-
expireAfterWrite
Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.When
durationis zero, elements will be evicted immediately after being loaded into the cache. This has the same effect as invokingmaximumSize(0). It can be useful in testing, or to disable caching temporarily without a code change.Expired entries may be counted by
Cache.size(), but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future.- Parameters:
duration- the length of time after an entry is created that it should be automatically removedunit- the unit thatdurationis expressed in- Returns:
- This for chaining
- Throws:
IllegalArgumentException- ifdurationis negativeIllegalStateException- if the time to live or time to idle was already set
-
initialCapacity
Sets the minimum total size for the internal hash tables. For example, if the initial capacity is60, and the concurrency level is8, then eight segments are created, each having a hash table of size eight. Providing a large enough estimate at construction time avoids the need for expensive resizing operations later, but setting this value unnecessarily high wastes memory.- Parameters:
initialCapacity- - initial capacity- Returns:
- This for chaining
- Throws:
IllegalArgumentException- ifinitialCapacityis negativeIllegalStateException- if an initial capacity was already set
-
maximumSize
Specifies the maximum number of entries the cache may contain. Note that the cache may evict an entry before this limit is exceeded. As the cache size grows close to the maximum, the cache evicts entries that are less likely to be used again. For example, the cache may evict an entry because it hasn't been used recently or very often.When
sizeis zero, elements will be evicted immediately after being loaded into the cache. This has the same effect as invokingexpireAfterWrite(0, unit)orexpireAfterAccess(0, unit). It can be useful in testing, or to disable caching temporarily without a code change.- Parameters:
size- the maximum size of the cache- Returns:
- This for chaining
- Throws:
IllegalArgumentException- ifsizeis negativeIllegalStateException- if a maximum size was already set
-
removalListener
public <K1 extends K,V1 extends V> SafeCacheBuilder<K1,V1> removalListener(com.google.common.cache.RemovalListener<? super K1, ? super V1> listener) Specifies a listener instance, which all caches built using thisCacheBuilderwill notify each time an entry is removed from the cache by any means.Each cache built by this
CacheBuilderafter this method is called invokes the supplied listener after removing an element for any reason (see removal causes inRemovalCause). It will invoke the listener during invocations of any of that cache's public methods (even read-only methods).Important note: Instead of returning this as a
CacheBuilderinstance, this method returnsCacheBuilder<K1, V1>. From this point on, either the original reference or the returned reference may be used to complete configuration and build the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from building caches whose key or value types are incompatible with the types accepted by the listener already provided; theCacheBuildertype cannot do this. For best results, simply use the standard method-chaining idiom, as illustrated in the documentation at top, configuring aCacheBuilderand building yourCacheall in a single statement.Warning: if you ignore the above advice, and use this
CacheBuilderto build a cache whose key or value type is incompatible with the listener, you will likely experience aClassCastExceptionat some undefined point in the future.- Type Parameters:
K1- Key typeV1- Value type- Parameters:
listener- - removal listener- Returns:
- This for chaining
- Throws:
IllegalStateException- if a removal listener was already set
-
ticker
Specifies a nanosecond-precision time source for use in determining when entries should be expired. By default,System.nanoTime()is used.The primary intent of this method is to facilitate testing of caches which have been configured with
expireAfterWrite(long, java.util.concurrent.TimeUnit)orexpireAfterAccess(long, java.util.concurrent.TimeUnit).- Parameters:
ticker- - ticker- Returns:
- This for chaining
- Throws:
IllegalStateException- if a ticker was already set
-
softValues
Specifies that each value (not key) stored in the cache should be wrapped in aSoftReference(by default, strong references are used). Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand.Warning: in most circumstances it is better to set a per-cache maximum size instead of using soft references. You should only use this method if you are well familiar with the practical consequences of soft references.
Note: when this method is used, the resulting cache will use identity (
==) comparison to determine equality of values.- Returns:
- This for chaining
- Throws:
IllegalStateException- if the value strength was already set
-
weakKeys
Specifies that each key (not value) stored in the cache should be wrapped in aWeakReference(by default, strong references are used).Warning: when this method is used, the resulting cache will use identity (
==) comparison to determine equality of keys.- Returns:
- This for chaining
- Throws:
IllegalStateException- if the key strength was already set
-
weakValues
Specifies that each value (not key) stored in the cache should be wrapped in aWeakReference(by default, strong references are used).Weak values will be garbage collected once they are weakly reachable. This makes them a poor candidate for caching; consider
softValues()instead.Note: when this method is used, the resulting cache will use identity (
==) comparison to determine equality of values.- Returns:
- This for chaining
- Throws:
IllegalStateException- if the value strength was already set
-
build
public <K1 extends K,V1 extends V> ConcurrentMap<K1,V1> build(com.google.common.cache.CacheLoader<? super K1, V1> loader) Returns the cache wrapped as a ConcurrentMap.We can't return the direct Cache instance as it changed in Guava 13.
- Type Parameters:
K1- Key typeV1- Value type- Parameters:
loader- - cache loader- Returns:
- The cache as a a map.
-