public class Cache2kBuilder<K,V> extends Object
Cache
instance. The usage is:
Cache<Long, List<String>> c =
new Cache2kBuilder<Long, List<String>>() {}
.name("myCache")
.eternal(true)
.build();
Caches belong to a cache manager. If no cache manager is set explicitly via
manager
the default cache manager will be used, as defined by
CacheManager.getInstance()
.
To create a cache from a known configuration in a specified cache manager, use:
CacheManager manager = ...
CacheConfiguration<Long, List<String>> config = ...
Cache<Long, List<String>> c =
Cache2kBuilder.of(config)
.manager(manager)
.build();
To create a cache without type parameters or Cache<Object,Object>
, use
forUnknownTypes()
.
Modifier | Constructor and Description |
---|---|
protected |
Cache2kBuilder()
Constructor to override for the usage pattern:
|
Modifier and Type | Method and Description |
---|---|
Cache2kBuilder<K,V> |
addAsyncListener(CacheEntryOperationListener<K,V> listener)
A set of listeners.
|
Cache2kBuilder<K,V> |
addCacheClosedListener(CacheClosedListener listener)
Listener that is called after a cache is closed.
|
Cache2kBuilder<K,V> |
addListener(CacheEntryOperationListener<K,V> listener)
Add a listener.
|
Cache2kBuilder<K,V> |
asyncListenerExecutor(Executor v)
Executor for asynchronous listeners.
|
Cache2kBuilder<K,V> |
boostConcurrency(boolean f)
When
true , optimize for high core counts and applications that do lots of mutations
in the cache. |
Cache<K,V> |
build()
Builds a cache with the specified configuration parameters.
|
IntCache<V> |
buildForIntKey()
Deprecated.
Will be removed in version 2.0
|
LongCache<V> |
buildForLongKey()
Deprecated.
Will be removed in version 2.0
|
Cache2kBuilder<K,V> |
disableLastModificationTime(boolean flag)
Deprecated.
|
Cache2kBuilder<K,V> |
disableMonitoring(boolean f)
Disables reporting of cache metrics to monitoring systems.
|
Cache2kBuilder<K,V> |
disableStatistics(boolean flag)
By default statistic gathering is enabled.
|
Cache2kBuilder<K,V> |
enableJmx(boolean f)
When
true expose statistics via JMX. |
Cache2kBuilder<K,V> |
entryCapacity(long v)
The maximum number of entries hold by the cache.
|
Cache2kBuilder<K,V> |
eternal(boolean v)
When set to
true , cached values do not expire by time. |
Cache2kBuilder<K,V> |
exceptionPropagator(ExceptionPropagator<K> ep)
Sets customization for propagating loader exceptions.
|
Cache2kBuilder<K,V> |
executor(Executor v)
Executor for asynchronous operations.
|
Cache2kBuilder<K,V> |
expireAfterWrite(long v,
TimeUnit u)
Time duration after insert or updated an cache entry expires.
|
Cache2kBuilder<K,V> |
expiryPolicy(ExpiryPolicy<K,V> c)
Set expiry policy to use.
|
static Cache2kBuilder |
forUnknownTypes()
|
CacheManager |
getManager()
Get the associated cache manager.
|
Cache2kBuilder<K,V> |
keepDataAfterExpired(boolean v)
Expired data is kept in the cache until the entry is evicted.
|
<K2> Cache2kBuilder<K2,V> |
keyType(CacheType<K2> t)
The used type of the cache key.
|
<K2> Cache2kBuilder<K2,V> |
keyType(Class<K2> t)
The used type of the cache key.
|
Cache2kBuilder<K,V> |
loader(AdvancedCacheLoader<K,V> l)
Enables read through operation and sets a cache loader.
|
Cache2kBuilder<K,V> |
loader(AsyncCacheLoader<K,V> l)
Enables read through operation and sets a cache loader.
|
Cache2kBuilder<K,V> |
loader(CacheLoader<K,V> l)
Enables read through operation and sets a cache loader.
|
Cache2kBuilder<K,V> |
loader(FunctionalCacheLoader<K,V> l)
Enables read through operation and sets a cache loader.
|
Cache2kBuilder<K,V> |
loaderExecutor(Executor v)
Thread pool / executor service to use for asynchronous load operations.
|
Cache2kBuilder<K,V> |
loaderThreadCount(int v)
If no separate executor is set via
loaderExecutor(Executor) the cache will
create a separate thread pool used exclusively by it. |
Cache2kBuilder<K,V> |
manager(CacheManager manager)
The manager, the created cache will belong to.
|
Cache2kBuilder<K,V> |
maximumWeight(long v)
Specifies the maximum weight of entries the cache may contain.
|
Cache2kBuilder<K,V> |
maxRetryInterval(long v,
TimeUnit u)
If a loader exception happens, this is the maximum time interval after a
retry attempt is made.
|
Cache2kBuilder<K,V> |
name(Class<?> clazz)
Sets a cache name from the fully qualified class name.
|
Cache2kBuilder<K,V> |
name(Class<?> clazz,
String fieldName)
Constructs a cache name out of the class name and field name.
|
Cache2kBuilder<K,V> |
name(String v)
Sets the name of a cache.
|
Cache2kBuilder<K,V> |
name(String uniqueName,
Class<?> clazz,
String fieldName)
Constructs a cache name out of the class name, a field name and a unique name identifying the
component in the application.
|
static <K,V> Cache2kBuilder<K,V> |
of(Cache2kConfiguration<K,V> c)
Create a builder from the configuration.
|
static <K,V> Cache2kBuilder<K,V> |
of(Class<K> keyType,
Class<V> valueType)
Create a new cache builder for key and value types of classes with no generic parameters.
|
Cache2kBuilder<K,V> |
permitNullValues(boolean flag)
When
true , null values are allowed in the cache. |
Cache2kBuilder<K,V> |
prefetchExecutor(Executor v)
Thread pool / executor service to use for refresh ahead and prefetch operations.
|
Cache2kBuilder<K,V> |
recordRefreshedTime(boolean flag)
Enables that time of an refresh (means update or freshness check of a value) is
available at
MutableCacheEntry.getRefreshedTime() . |
Cache2kBuilder<K,V> |
refreshAhead(boolean f)
When
true , enable background refresh / refresh ahead. |
Cache2kBuilder<K,V> |
resilienceDuration(long v,
TimeUnit u)
Time span the cache will suppress loader exceptions if a value is available from
a previous load.
|
Cache2kBuilder<K,V> |
resiliencePolicy(ResiliencePolicy<K,V> v)
Sets a custom resilience policy to control the cache behavior in the presence
of exceptions from the loader.
|
Cache2kBuilder<K,V> |
retryInterval(long v,
TimeUnit u)
If a loader exception happens, this is the time interval after a
retry attempt is made.
|
Cache2kBuilder<K,V> |
sharpExpiry(boolean f)
By default the expiry time is not exact, which means, a value might be visible a few
milliseconds after the time of expiry.
|
Cache2kBuilder<K,V> |
storeByReference(boolean v)
Ensure that the cache value is stored via direct object reference and that
no serialization takes place.
|
Cache2kBuilder<K,V> |
strictEviction(boolean flag)
To increase performance cache2k optimizes the eviction and does eviction in
greater chunks.
|
Cache2kBuilder<K,V> |
suppressExceptions(boolean v)
Suppress an exception from the cache loader, if there is previous data.
|
Cache2kBuilder<K,V> |
timeReference(TimeReference v)
Clock to be used by the cache as time reference.
|
Cache2kConfiguration<K,V> |
toConfiguration()
Returns the configuration object this builder operates on.
|
<V2> Cache2kBuilder<K,V2> |
valueType(CacheType<V2> t)
Sets the value type to use.
|
<V2> Cache2kBuilder<K,V2> |
valueType(Class<V2> t)
Sets the value type to use.
|
Cache2kBuilder<K,V> |
weigher(Weigher<K,V> v)
Set the weigher to be used to calculate the entry weight.
|
Cache2kBuilder<K,V> |
with(ConfigurationSectionBuilder<? extends ConfigurationSection>... sectionBuilders)
Add a new configuration sub section.
|
Cache2kBuilder<K,V> |
wrappingLoader(AdvancedCacheLoader<K,LoadDetail<V>> l)
Enables read through operation and sets a cache loader
|
Cache2kBuilder<K,V> |
wrappingLoader(CacheLoader<K,LoadDetail<V>> l)
Enables read through operation and sets a cache loader
|
Cache2kBuilder<K,V> |
wrappingLoader(FunctionalCacheLoader<K,LoadDetail<V>> l)
Enables read through operation and sets a cache loader
|
Cache2kBuilder<K,V> |
writer(CacheWriter<K,V> w)
Enables write through operation and sets a writer customization that gets
called synchronously upon cache mutations.
|
protected Cache2kBuilder()
Cache<Long, List<String>> c =
new Cache2kBuilder<Long, List<String>>() {}
.name("myCache")
.eternal(true)
.build();
The builder extracts the generic type parameters from the anonymous subclass.public static Cache2kBuilder forUnknownTypes()
public static <K,V> Cache2kBuilder<K,V> of(Class<K> keyType, Class<V> valueType)
keyType(Class)
,
valueType(Class)
public static <K,V> Cache2kBuilder<K,V> of(Cache2kConfiguration<K,V> c)
public final Cache2kBuilder<K,V> manager(CacheManager manager)
manager
- The manager the created cache should belong to,
or null
if the default cache manager should be usedIllegalStateException
- if the manager is not provided immediately after the builder
is created.public final <K2> Cache2kBuilder<K2,V> keyType(Class<K2> t)
equals
and hashCode
method. Arrays are not valid for cache keys.IllegalArgumentException
- in case the type is illegalfor a general discussion on types
public final <V2> Cache2kBuilder<K,V2> valueType(Class<V2> t)
IllegalArgumentException
- in case the type is illegalfor a general discussion on types
public final <K2> Cache2kBuilder<K2,V> keyType(CacheType<K2> t)
equals
and hashCode
method. Arrays are not valid for cache keys.IllegalArgumentException
- in case the type is illegalfor a general discussion on types
public final <V2> Cache2kBuilder<K,V2> valueType(CacheType<V2> t)
IllegalArgumentException
- in case the type is illegalfor a general discussion on types
public final Cache2kBuilder<K,V> name(String uniqueName, Class<?> clazz, String fieldName)
webImagePool~com.example.ImagePool.id2Image
See name(String)
for a general discussion about cache names.
uniqueName
- unique name differentiating multiple components of the same type.
May be null
.name(String)
public final Cache2kBuilder<K,V> name(Class<?> clazz, String fieldName)
com.example.ImagePool.id2Image
See name(String)
for a general discussion about cache names.
name(String)
public final Cache2kBuilder<K,V> name(Class<?> clazz)
See name(String)
for a general discussion about cache names.
name(String)
public final Cache2kBuilder<K,V> name(String v)
If a name is not specified the cache generates a name automatically. The name is
inferred from the call stack trace and contains the simple class name, the method and
the line number of the of the caller to build()
. The name also contains
a random number. Automatically generated names don't allow reliable management, logging and
additional configuration of caches. If no name is set, build()
will always create
a new cache with a new unique name within the cache manager. Automatically generated
cache names start with the character '_'
as prefix to separate the names from the
usual class name space.
For maximum compatibility cache names should only be composed with the characters
[-_.a-zA-Z0-9]
. The characters {}|\^&=";:<>*?/
are not allowed in a cache name.
The reason for restricting the characters in names, is that the names may be used to derive
other resource names from it, e.g. for file based storage. The characters *
and
?
are used for wildcards in JMX and cannot be used in an object name.
The method is overloaded with variants to provide a naming convention of names.
For brevity within log messages and other displays the cache name may be shortened if the manager name is included as prefix.
Cache.getName()
public final Cache2kBuilder<K,V> keepDataAfterExpired(boolean v)
false
AdvancedCacheLoader
public final Cache2kBuilder<K,V> entryCapacity(long v)
The value Long.MAX_VALUE
means the capacity is not limited.
The default value is 2000. The default value is conservative, so the application will usually run stable without tuning or setting a reasonable size.
public final Cache2kBuilder<K,V> eternal(boolean v)
true
, cached values do not expire by time. Entries will need to be removed
from the cache explicitly or will be evicted if capacity constraints are reached.
Setting eternal to false
signals that the data should expire, but there is no
predefined expiry value at programmatic level. This value needs to be set by other
means, e.g. within a configuration file.
The default behavior of the cache is identical to the setting of eternal. Entries will not expire. When eternal was set explicitly it cannot be reset to another value afterwards. This should protect against misconfiguration.
Exceptions: If set to eternal with default setting and if there is no
explicit expiry configured for exceptions with retryInterval(long, TimeUnit)
,
exceptions will not be cached and expire immediately.
IllegalArgumentException
- in case a previous setting is resetpublic final Cache2kBuilder<K,V> suppressExceptions(boolean v)
retryInterval(long, TimeUnit)
.
Exception suppression is only active when entries expire (eternal is not true) or the
explicit configuration of the timing parameters for resilience, e.g.
resilienceDuration(long, TimeUnit)
. Check the user guide chapter for details.
Exception suppression is enabled by default. Setting this to false
, will disable
exceptions suppression (aka resilience).
public final Cache2kBuilder<K,V> expireAfterWrite(long v, TimeUnit u)
eternal(boolean)
. The expiry
happens via a timer event and is lagging a few milliseconds. For exact
expiry use an ExpiryPolicy
and enable sharpExpiry(boolean)
.
If an ExpiryPolicy
is specified, the maximum expiry duration
is capped to the value specified here.
A value of 0
means every entry should expire immediately. This can be useful
to disable caching via configuration.
IllegalArgumentException
- if eternal(boolean)
was set to truepublic final Cache2kBuilder<K,V> exceptionPropagator(ExceptionPropagator<K> ep)
CacheLoaderException
.public final Cache2kBuilder<K,V> loader(FunctionalCacheLoader<K,V> l)
FunctionalCacheLoader
, CacheLoader
,
AdvancedCacheLoader
.for general discussion on cache loaders
public final Cache2kBuilder<K,V> loader(CacheLoader<K,V> l)
FunctionalCacheLoader
, CacheLoader
,
AdvancedCacheLoader
.for general discussion on cache loaders
public final Cache2kBuilder<K,V> loader(AdvancedCacheLoader<K,V> l)
FunctionalCacheLoader
, CacheLoader
,
AdvancedCacheLoader
.for general discussion on cache loaders
public final Cache2kBuilder<K,V> loader(AsyncCacheLoader<K,V> l)
FunctionalCacheLoader
, CacheLoader
,
AdvancedCacheLoader
.for general discussion on cache loaders
public final Cache2kBuilder<K,V> wrappingLoader(AdvancedCacheLoader<K,LoadDetail<V>> l)
for general discussion on cache loaders
public final Cache2kBuilder<K,V> wrappingLoader(FunctionalCacheLoader<K,LoadDetail<V>> l)
for general discussion on cache loaders
public final Cache2kBuilder<K,V> wrappingLoader(CacheLoader<K,LoadDetail<V>> l)
for general discussion on cache loaders
public final Cache2kBuilder<K,V> writer(CacheWriter<K,V> w)
public final Cache2kBuilder<K,V> addCacheClosedListener(CacheClosedListener listener)
public final Cache2kBuilder<K,V> addListener(CacheEntryOperationListener<K,V> listener)
listener
- The listener to addIllegalArgumentException
- if an identical listener is already added.public final Cache2kBuilder<K,V> addAsyncListener(CacheEntryOperationListener<K,V> listener)
listener
- The listener to addIllegalArgumentException
- if an identical listener is already added.public final Cache2kBuilder<K,V> expiryPolicy(ExpiryPolicy<K,V> c)
If this is specified the maximum expiry time is still limited to the value in
expireAfterWrite(long, java.util.concurrent.TimeUnit)
. If expireAfterWrite(long, java.util.concurrent.TimeUnit)
is set to 0 then expiry calculation is not used, all entries expire immediately.
If no maximum expiry is specified via expireAfterWrite(long, java.util.concurrent.TimeUnit)
at least the
resilienceDuration(long, java.util.concurrent.TimeUnit)
needs to be specified, if resilience should be enabled.
public final Cache2kBuilder<K,V> refreshAhead(boolean f)
true
, enable background refresh / refresh ahead. After the expiry time of a
value is reached, the loader is invoked to fetch a fresh value. The old value will be
returned by the cache, although it is expired, and will be replaced by the new value,
once the loader is finished. In the case there are not enough loader threads available,
the value will expire immediately and the next get()
request will trigger the load.
Once refreshed, the entry is in a trial period. If it is not accessed until the next
expiry, no refresh will be done and the entry expires regularly. This means that the
time an entry stays within the trial period is determined by the configured expiry time
or the ExpiryPolicy
. In case an entry is not accessed any more it needs to
reach the expiry time twice before removed from the cache.
The number of threads used to do the refresh are configured via
loaderThreadCount(int)
By default, refresh ahead is not enabled.
public final Cache2kBuilder<K,V> sharpExpiry(boolean f)
true
, means that values will not be visible when the time is reached that
ExpiryPolicy
returned. This has no effect on expireAfterWrite(long, TimeUnit)
.public final Cache2kBuilder<K,V> loaderThreadCount(int v)
loaderExecutor(Executor)
the cache will
create a separate thread pool used exclusively by it. Defines the maximum number of threads
this cache should use for calls to the CacheLoader
. The default is one thread
per available CPU.
If a separate executor is defined the parameter has no effect.
public final Cache2kBuilder<K,V> storeByReference(boolean v)
If this value is not set to true this means: The key and value objects need to have a defined serialization mechanism and the cache may choose to transfer off the heap. For cache2k version 1.0 this value has no effect. It should be used by application developers to future proof the applications with upcoming versions.
public final Cache2kBuilder<K,V> retryInterval(long v, TimeUnit u)
maxRetryInterval(long, java.util.concurrent.TimeUnit)
.public final Cache2kBuilder<K,V> maxRetryInterval(long v, TimeUnit u)
By default identical to resilienceDuration(long, java.util.concurrent.TimeUnit)
public final Cache2kBuilder<K,V> resilienceDuration(long v, TimeUnit u)
suppressExceptions(boolean)
is switched off, this setting
has no effect.
Defaults to expireAfterWrite(long, java.util.concurrent.TimeUnit)
. If suppressExceptions(boolean)
is switched off, this setting has no effect.
public final Cache2kBuilder<K,V> resiliencePolicy(ResiliencePolicy<K,V> v)
expireAfterWrite(long, java.util.concurrent.TimeUnit)
is set to 0.public final Cache2kBuilder<K,V> with(ConfigurationSectionBuilder<? extends ConfigurationSection>... sectionBuilders)
ConfigurationWithSections
public final Cache2kBuilder<K,V> strictEviction(boolean flag)
public final Cache2kBuilder<K,V> permitNullValues(boolean flag)
true
, null
values are allowed in the cache. In the default configuration
null
values are prohibited.
See the chapter in the user guide for details on null
values.
When used within Spring, null
are allowed by default.
public final Cache2kBuilder<K,V> disableStatistics(boolean flag)
true
will disable all
statistics that have significant overhead. Whether the values become accessible with JMX is
controlled by enableJmx(boolean)
.@Deprecated public final Cache2kBuilder<K,V> disableLastModificationTime(boolean flag)
recordRefreshedTime(boolean)
.public final Cache2kBuilder<K,V> recordRefreshedTime(boolean flag)
MutableCacheEntry.getRefreshedTime()
.MutableCacheEntry.getRefreshedTime()
public final Cache2kBuilder<K,V> boostConcurrency(boolean f)
true
, optimize for high core counts and applications that do lots of mutations
in the cache. When switched on, the cache will occupy slightly more memory and eviction
efficiency may drop slightly. This overhead is negligible for big cache sizes (100K and more).
Typical interactive do not need to enable this. May improve concurrency for applications that utilize all cores and cache operations account for most CPU cycles.
public final Cache2kBuilder<K,V> enableJmx(boolean f)
true
expose statistics via JMX. Disabled by default. It is possible to enable
JMX even there is no cache name specified with name(String)
, since a name will
be generated internally, thus enabling JMX by default for all caches is feasible.public final Cache2kBuilder<K,V> disableMonitoring(boolean f)
public final Cache2kBuilder<K,V> loaderExecutor(Executor v)
loaderThreadCount(int)
,
prefetchExecutor(Executor)
public final Cache2kBuilder<K,V> prefetchExecutor(Executor v)
loaderExecutor(Executor)
or a cache local pool is created.
The executor for refresh operations may reject execution when not enough resources are available. In this case the cache entry expires.
loaderThreadCount(int)
,
loaderExecutor(Executor)
public final Cache2kBuilder<K,V> executor(Executor v)
ForkJoinPool.commonPool()
is used by default or an internal
executor is used that has unbounded thread capacity otherwise.public final Cache2kBuilder<K,V> asyncListenerExecutor(Executor v)
public final Cache2kBuilder<K,V> timeReference(TimeReference v)
public final Cache2kBuilder<K,V> weigher(Weigher<K,V> v)
maximumWeight(long)
needs to be specified as well. Using a weigher has a slightly
performance impact on the update of existing entries.public final Cache2kBuilder<K,V> maximumWeight(long v)
Weigher
must be specified via weigher(org.cache2k.Weigher<K, V>)
.
The weight of an entry does not influence which entry is evicted next, but is only used to constrain the capacity of the cache. The cache implementation tries the best to keep the cache within its maximum weight limit, but eviction may kick in before or after reaching the limit.
The maximum weight setting cannot be used together with entryCapacity(long)
.
public final Cache2kConfiguration<K,V> toConfiguration()
build()
is called. The method does not
return the effective configuration if additional external/XML configuration is present, since
this is applied when build
is called. On the other hand, the method can be used
to inspect the effective configuration after build
completed.public final CacheManager getManager()
public final Cache<K,V> build()
If XML configuration is present, the section for the cache name is looked up and the configuration in it applied, before the cache is build.
IllegalArgumentException
- if a cache of the same name is already active in the
cache managerIllegalArgumentException
- if a configuration entry for the named cache is required but
not presentpublic final IntCache<V> buildForIntKey()
build()
except that it checks that
the key type is Integer
and casts the created cache to the specialized
interface.IllegalArgumentException
- if a cache of the same name is already active in the
cache managerIllegalArgumentException
- if key type is unexpectedIllegalArgumentException
- if a configuration entry for the named cache is required but
not presentpublic final LongCache<V> buildForLongKey()
build()
except that it checks that
the key type is Integer
and casts the created cache to the specialized
interface.IllegalArgumentException
- if a cache of the same name is already active in the
cache managerIllegalArgumentException
- if key type is unexpectedIllegalArgumentException
- if a configuration entry for the named cache is required but
not presentcache2k API documentation. Copyright © 2000–2020 headissue GmbH, Munich.