|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object com.google.common.cache.CacheBuilder<K,V>
K
- the base key type for all caches created by this builderV
- the base value type for all caches created by this builder@Beta public final class CacheBuilder<K,V>
A builder of Cache
instances having any combination of the following features:
Usage example:
Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.weakKeys()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
These features are all optional.
The returned cache is implemented as a hash table with similar performance characteristics to
ConcurrentHashMap
. It implements the optional operations Cache.invalidate(java.lang.Object)
,
Cache.invalidateAll()
, Cache.size()
, Cache.stats()
, and Cache.asMap()
,
with the following qualifications:
invalidateAll
method will invalidate all cached entries prior to returning, and
removal notifications will be issued for all invalidated entries.
asMap
view supports removal operations, but no other modifications.
asMap
view (and its collection views) have weakly consistent iterators.
This means that they are safe for concurrent use, but if other threads modify the cache after
the iterator is created, it is undefined which of these changes, if any, are reflected in
that iterator. These iterators never throw ConcurrentModificationException
.
Note: by default, the returned cache uses equality comparisons (the
equals
method) to determine equality for keys or values. However, if
weakKeys()
was specified, the cache uses identity (==
)
comparisons instead for keys. Likewise, if weakValues()
or softValues()
was
specified, the cache uses identity comparisons for values.
If soft or weak references were requested, it is possible for a key or value present in the the cache to be reclaimed by the garbage collector. If this happens, the entry automatically disappears from the cache. A partially-reclaimed entry is never exposed to the user.
Certain cache configurations will result in the accrual of periodic maintenance tasks which
will be performed during write operations, or during occasional read operations in the absense of
writes. The Cache.cleanUp()
method of the returned cache will also perform maintenance, but
calling it should not be necessary with a high throughput cache. Only caches built with
removalListener,
expireAfterWrite,
expireAfterAccess,
weakKeys, weakValues,
or softValues perform periodic maintenance.
The caches produced by CacheBuilder
are serializable, and the deserialized caches
retain all the configuration properties of the original cache. Note that the serialized form does
not include cache contents, but only configuration.
Method Summary | ||
---|---|---|
|
build(CacheLoader<? super K1,V1> loader)
Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader . |
|
CacheBuilder<K,V> |
concurrencyLevel(int concurrencyLevel)
Guides the allowed concurrency among update operations. |
|
CacheBuilder<K,V> |
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. |
|
CacheBuilder<K,V> |
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. |
|
CacheBuilder<K,V> |
initialCapacity(int initialCapacity)
Sets the minimum total size for the internal hash tables. |
|
CacheBuilder<K,V> |
maximumSize(int size)
Specifies the maximum number of entries the cache may contain. |
|
static CacheBuilder<Object,Object> |
newBuilder()
Constructs a new CacheBuilder instance with default settings, including strong keys,
strong values, and no automatic eviction of any kind. |
|
|
removalListener(RemovalListener<? super K1,? super V1> listener)
Specifies a listener instance, which all caches built using this CacheBuilder will
notify each time an entry is removed from the cache by any means. |
|
CacheBuilder<K,V> |
softValues()
Specifies that each value (not key) stored in the cache should be wrapped in a SoftReference (by default, strong references are used). |
|
CacheBuilder<K,V> |
ticker(Ticker ticker)
Specifies a nanosecond-precision time source for use in determining when entries should be expired. |
|
String |
toString()
Returns a string representation for this CacheBuilder instance. |
|
CacheBuilder<K,V> |
weakKeys()
Specifies that each key (not value) stored in the cache should be wrapped in a WeakReference (by default, strong references are used). |
|
CacheBuilder<K,V> |
weakValues()
Specifies that each value (not key) stored in the cache should be wrapped in a WeakReference (by default, strong references are used). |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
Method Detail |
---|
public static CacheBuilder<Object,Object> newBuilder()
CacheBuilder
instance with default settings, including strong keys,
strong values, and no automatic eviction of any kind.
public CacheBuilder<K,V> initialCapacity(int initialCapacity)
60
, and the concurrency level is 8
, 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.
IllegalArgumentException
- if initialCapacity
is negative
IllegalStateException
- if an initial capacity was already setpublic CacheBuilder<K,V> concurrencyLevel(int concurrencyLevel)
Note:The default may change in the future. If you care about this value, you should always choose it explicitly.
IllegalArgumentException
- if concurrencyLevel
is nonpositive
IllegalStateException
- if a concurrency level was already setpublic CacheBuilder<K,V> maximumSize(int size)
When size
is zero, elements will be evicted immediately after being loaded into the
cache. This has the same effect as invoking expireAfterWrite
(0, unit)
or expireAfterAccess
(0,
unit)
. It can be useful in testing, or to disable caching temporarily without a code change.
size
- the maximum size of the cache
IllegalArgumentException
- if size
is negative
IllegalStateException
- if a maximum size was already setpublic CacheBuilder<K,V> weakKeys()
WeakReference
(by default, strong references are used).
Warning: when this method is used, the resulting cache will use identity (==
)
comparison to determine equality of keys.
Entries with keys that have been garbage collected may be counted by Cache.size()
, but
will never be visible to read or write operations. Entries with garbage collected keys are
cleaned up as part of the routine maintenance described in the class javadoc.
IllegalStateException
- if the key strength was already setpublic CacheBuilder<K,V> weakValues()
WeakReference
(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.
Entries with values that have been garbage collected may be counted by Cache.size()
,
but will never be visible to read or write operations. Entries with garbage collected keys are
cleaned up as part of the routine maintenance described in the class javadoc.
IllegalStateException
- if the value strength was already setpublic CacheBuilder<K,V> softValues()
SoftReference
(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.
Entries with values that have been garbage collected may be counted by Cache.size()
,
but will never be visible to read or write operations. Entries with garbage collected values
are cleaned up as part of the routine maintenance described in the class javadoc.
IllegalStateException
- if the value strength was already setpublic CacheBuilder<K,V> expireAfterWrite(long duration, TimeUnit unit)
When duration
is zero, elements will be evicted immediately after being loaded into
the cache. This has the same effect as invoking maximumSize
(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 cleaned up as part of the routine maintenance described
in the class javadoc.
duration
- the length of time after an entry is created that it should be automatically
removedunit
- the unit that duration
is expressed in
IllegalArgumentException
- if duration
is negative
IllegalStateException
- if the time to live or time to idle was already setpublic CacheBuilder<K,V> expireAfterAccess(long duration, TimeUnit unit)
Cache.get(K)
and Cache.getUnchecked(K)
, but not by operations on the view returned by
Cache.asMap()
.
When duration
is zero, elements will be evicted immediately after being loaded into
the cache. This has the same effect as invoking maximumSize
(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 cleaned up as part of the routine maintenance described
in the class javadoc.
duration
- the length of time after an entry is last accessed that it should be
automatically removedunit
- the unit that duration
is expressed in
IllegalArgumentException
- if duration
is negative
IllegalStateException
- if the time to idle or time to live was already setpublic CacheBuilder<K,V> ticker(Ticker ticker)
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)
or expireAfterAccess(long, java.util.concurrent.TimeUnit)
.
IllegalStateException
- if a ticker was already set@CheckReturnValue public <K1 extends K,V1 extends V> CacheBuilder<K1,V1> removalListener(RemovalListener<? super K1,? super V1> listener)
CacheBuilder
will
notify each time an entry is removed from the cache by any means.
Each cache built by this CacheBuilder
after this method is called invokes the
supplied listener after removing an element for any reason (see removal causes in RemovalCause
). It will invoke the listener as part of the routine maintenance described
in the class javadoc.
Important note: Instead of returning this as a CacheBuilder
instance, this method returns CacheBuilder<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; the CacheBuilder
type cannot do this. For best results,
simply use the standard method-chaining idiom, as illustrated in the documentation at top,
configuring a CacheBuilder
and building your Cache
all in a single statement.
Warning: if you ignore the above advice, and use this CacheBuilder
to build
a cache whose key or value type is incompatible with the listener, you will likely experience
a ClassCastException
at some undefined point in the future.
IllegalStateException
- if a removal listener was already setpublic <K1 extends K,V1 extends V> Cache<K1,V1> build(CacheLoader<? super K1,V1> loader)
CacheLoader
. If another thread is currently
loading the value for this key, simply waits for that thread to finish and returns its
loaded value. Note that multiple threads can concurrently load values for distinct keys.
This method does not alter the state of this CacheBuilder
instance, so it can be
invoked again to create multiple independent caches.
loader
- the cache loader used to obtain new values
public String toString()
toString
in class Object
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |