Class ConcurrentCache
java.lang.Object
org.apache.derby.impl.services.cache.ConcurrentCache
- All Implemented Interfaces:
CacheManager
A cache manager based on the utilities found in the
java.util.concurrent package. It allows multiple threads to
access the cache concurrently without blocking each other, given that they
request different objects and the requested objects are present in the
cache.
All methods of this class should be thread safe. When exclusive access to an
entry is required, it is achieved by calling the lock() method
on the CacheEntry object. To ensure that the entry is always
unlocked, all calls to CacheEntry.lock() should be followed by
a try block with a finally clause that unlocks the
entry.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final ConcurrentHashMap<Object, CacheEntry> Map with all the cached objects.private BackgroundCleanerBackground cleaner which can be used to clean cached objects in a separate thread to avoid blocking the user threads.private booleanFlag that tells if hit/miss/eviction counts should be collected.private final AtomicLongThe number of evictions from the cache.private final AtomicLongThe number of cache hits.private final CacheableFactoryFactory which createsCacheables.private final intThe maximum size (number of elements) for this cache.private ObjectThe identifier of the MBean that allows monitoring of this instance.private final AtomicLongThe number of cache misses.private final StringName of this cache.private final ReplacementPolicyReplacement policy to be used for this cache.private booleanFlag that indicates whether this cache instance has been shut down. -
Constructor Summary
ConstructorsConstructorDescriptionConcurrentCache(CacheableFactory holderFactory, String name, int initialSize, int maxSize) Creates a new cache manager. -
Method Summary
Modifier and TypeMethodDescriptionvoidageOut()Remove all objects that are not kept and not dirty.voidClean all dirty objects matching a partial key.voidcleanAll()Clean all dirty objects in the cache.(package private) voidcleanAndUnkeepEntry(CacheEntry entry, Cacheable item) Clean an entry in the cache and decrement its keep count.private voidcleanCache(Matchable partialKey) Clean all dirty objects matching a partial key.(package private) voidcleanEntry(CacheEntry entry) Clean an entry in the cache.private voidCount an eviction from the cache.private voidcountHit()Count a cache hit.private voidCount a cache miss.Create an object in the cache.voidDeregister the MBean that monitors this cache.booleanDiscard all unused objects that match a partial key.(package private) voidevictEntry(Object key) Evict an entry to make room for a new entry that is being inserted into the cache.Find an object in the cache.findCached(Object key) Find an object in the cache.(package private) longGet the number of allocated entries in the cache.(package private) BackgroundCleaner(package private) booleanCheck if collection of hit/miss/eviction counts is enabled.private CacheEntryGet the entry associated with the specified key from the cache.(package private) longGet the number of evictions from the cache.(package private) longGet the number of cache hits.(package private) longGet the maximum number of entries in the cache.(package private) longGet the number of cache misses.(package private) ReplacementPolicyReturn theReplacementPolicyinstance for this cache.private static ObjectgetSystemModule(String factoryInterface) Privileged module lookup.(package private) longGet the number of cached objects.private CacheableinsertIntoFreeSlot(Object key, CacheEntry entry) Insert aCacheEntryinto a free slot in theReplacementPolicy's internal data structure, and return aCacheablethat the caller can reuse.voidregisterMBean(String dbName) Register an MBean that allows user to monitor this cache instance.voidRelease an object that has been fetched from the cache withfind(),findCached()orcreate().voidRemove an object from the cache.private voidremoveEntry(Object key) Remove an entry from the cache.(package private) voidsetCollectAccessCounts(boolean collect) Enable or disable collection of hit/miss/eviction counts.private voidsettingIdentityComplete(Object key, CacheEntry entry, Cacheable item) Complete the setting of the identity.voidshutdown()Shut down the cache.voiduseDaemonService(DaemonService daemon) Specify a daemon service that can be used to perform operations in the background.values()Return a collection view of all theCacheables in the cache.
-
Field Details
-
cache
Map with all the cached objects. -
holderFactory
Factory which createsCacheables. -
name
Name of this cache. -
maxSize
private final int maxSizeThe maximum size (number of elements) for this cache. -
replacementPolicy
Replacement policy to be used for this cache. -
mbean
The identifier of the MBean that allows monitoring of this instance. -
collectAccessCounts
private volatile boolean collectAccessCountsFlag that tells if hit/miss/eviction counts should be collected. -
hits
The number of cache hits. -
misses
The number of cache misses. -
evictions
The number of evictions from the cache. -
stopped
private volatile boolean stoppedFlag that indicates whether this cache instance has been shut down. When it has been stopped,find(),findCached()andcreate()will returnnull. The flag is declaredvolatileso that no synchronization is needed when it is accessed by concurrent threads. -
cleaner
Background cleaner which can be used to clean cached objects in a separate thread to avoid blocking the user threads.
-
-
Constructor Details
-
ConcurrentCache
ConcurrentCache(CacheableFactory holderFactory, String name, int initialSize, int maxSize) Creates a new cache manager.- Parameters:
holderFactory- factory which createsCacheablesname- the name of the cacheinitialSize- the initial capacity of the cachemaxSize- maximum number of elements in the cache
-
-
Method Details
-
getReplacementPolicy
ReplacementPolicy getReplacementPolicy()Return theReplacementPolicyinstance for this cache.- Returns:
- replacement policy
-
getEntry
Get the entry associated with the specified key from the cache. If the entry does not exist, insert an empty one and return it. The returned entry is always locked for exclusive access by the current thread, but not kept. If another thread is currently setting the identity of this entry, this method will block until the identity has been set.- Parameters:
key- the identity of the cached object- Returns:
- an entry for the specified key, always locked
-
removeEntry
Remove an entry from the cache. ItsCacheableis cleared and made available for other entries. This method should only be called if the entry is present in the cache and locked by the current thread.- Parameters:
key- the identity of the entry to remove
-
evictEntry
Evict an entry to make room for a new entry that is being inserted into the cache. Clear the identity of itsCacheableand set it tonull. When this method is called, the caller has already chosen theCacheablefor reuse. Therefore, this method won't callCacheEntry.free()as that would make theCacheablefree for reuse by other entries as well.The caller must have locked the entry that is about to be evicted.
- Parameters:
key- identity of the entry to remove
-
insertIntoFreeSlot
Insert aCacheEntryinto a free slot in theReplacementPolicy's internal data structure, and return aCacheablethat the caller can reuse. The entry must have been locked before this method is called.- Parameters:
key- the identity of the object being insertedentry- the entry that is being inserted- Returns:
- a
Cacheableobject that the caller can reuse - Throws:
StandardException- if an error occurs while inserting the entry or while allocating a newCacheable
-
settingIdentityComplete
Complete the setting of the identity. This includes notifying the threads that are waiting for the setting of the identity to complete, so that they can wake up and continue. If setting the identity failed, the entry will be removed from the cache.- Parameters:
key- the identity of the object being insertedentry- the entry which is going to hold the cached objectitem- aCacheableobject with the identity set (if the identity was successfully set), ornullif setting the identity failed
-
find
Find an object in the cache. If it is not present, add it to the cache. The returned object is kept untilrelease()is called.- Specified by:
findin interfaceCacheManager- Parameters:
key- identity of the object to find- Returns:
- the cached object, or
nullif it cannot be found - Throws:
StandardException- Standard Derby error policy.- See Also:
-
findCached
Find an object in the cache. If it is not present, returnnull. The returned object is kept untilrelease()is called.- Specified by:
findCachedin interfaceCacheManager- Parameters:
key- identity of the object to find- Returns:
- the cached object, or
nullif it's not in the cache - Throws:
StandardException- Standard Derby error policy.
-
create
Create an object in the cache. The object is kept untilrelease()is called.- Specified by:
createin interfaceCacheManager- Parameters:
key- identity of the object to createcreateParameter- parameters passed toCacheable.createIdentity()- Returns:
- a reference to the cached object, or
nullif the object cannot be created - Throws:
StandardException- if the object is already in the cache, or if some other error occurs- See Also:
-
release
Release an object that has been fetched from the cache withfind(),findCached()orcreate().- Specified by:
releasein interfaceCacheManager- Parameters:
item- aCacheablevalue
-
remove
Remove an object from the cache. The object must previously have been fetched from the cache withfind(),findCached()orcreate(). The user of the cache must make sure that only one caller executes this method on a cached object. This method will wait until the object has been removed (its keep count must drop to zero before it can be removed).- Specified by:
removein interfaceCacheManager- Parameters:
item- the object to remove from the cache- Throws:
StandardException- Standard Derby error policy.
-
cleanAll
Clean all dirty objects in the cache. All objects that existed in the cache at the time of the call will be cleaned. Objects added later may or may not be cleaned.- Specified by:
cleanAllin interfaceCacheManager- Throws:
StandardException- Standard Derby error policy.- See Also:
-
clean
Clean all dirty objects matching a partial key.- Specified by:
cleanin interfaceCacheManager- Parameters:
partialKey- the partial (or exact) key to match- Throws:
StandardException- Standard Derby error policy.
-
cleanCache
Clean all dirty objects matching a partial key. If no key is specified, clean all dirty objects in the cache.- Parameters:
partialKey- the partial (or exact) key to match, ornullto match all keys- Throws:
StandardException
-
cleanEntry
Clean an entry in the cache.- Parameters:
entry- the entry to clean- Throws:
StandardException- if an error occurs while cleaning
-
cleanAndUnkeepEntry
Clean an entry in the cache and decrement its keep count. The entry must be kept before this method is called, and it must contain the specifiedCacheable.- Parameters:
entry- the entry to cleanitem- the cached object contained in the entry- Throws:
StandardException- if an error occurs while cleaning
-
ageOut
public void ageOut()Remove all objects that are not kept and not dirty.- Specified by:
ageOutin interfaceCacheManager- See Also:
-
shutdown
Shut down the cache.- Specified by:
shutdownin interfaceCacheManager- Throws:
StandardException- Standard Derby error policy.
-
useDaemonService
Specify a daemon service that can be used to perform operations in the background. Callers must provide enough synchronization so that they have exclusive access to the cache when this method is called.- Specified by:
useDaemonServicein interfaceCacheManager- Parameters:
daemon- the daemon service to use
-
getBackgroundCleaner
BackgroundCleaner getBackgroundCleaner() -
discard
Discard all unused objects that match a partial key. Dirty objects will not be cleaned before their removal.- Specified by:
discardin interfaceCacheManager- Parameters:
partialKey- the partial (or exact) key, ornullto match all keys- Returns:
trueif all matching objects were removed,falseotherwise
-
values
Return a collection view of all theCacheables in the cache. There is no guarantee that the objects in the collection can be accessed in a thread-safe manner once this method has returned, so it should only be used for diagnostic purposes. (Currently, it is only used by theStatementCacheVTI.)- Specified by:
valuesin interfaceCacheManager- Returns:
- a collection view of the objects in the cache
-
registerMBean
Description copied from interface:CacheManagerRegister an MBean that allows user to monitor this cache instance. This is a no-op if the platform does not support Java Management Extensions (JMX).
The MBean will be automatically deregistered when
CacheManager.shutdown()is called, or it can be manually deregistered by callingCacheManager.deregisterMBean().- Specified by:
registerMBeanin interfaceCacheManager- Parameters:
dbName- the unique name of the database to which the cache belongs- Throws:
StandardException- if an error occurs when registering the MBean
-
deregisterMBean
public void deregisterMBean()Description copied from interface:CacheManagerDeregister the MBean that monitors this cache. If there is no MBean for this instance, this is a no-op.- Specified by:
deregisterMBeanin interfaceCacheManager
-
countHit
private void countHit()Count a cache hit. -
countMiss
private void countMiss()Count a cache miss. -
countEviction
private void countEviction()Count an eviction from the cache. -
setCollectAccessCounts
void setCollectAccessCounts(boolean collect) Enable or disable collection of hit/miss/eviction counts. -
getCollectAccessCounts
boolean getCollectAccessCounts()Check if collection of hit/miss/eviction counts is enabled. -
getHitCount
long getHitCount()Get the number of cache hits. -
getMissCount
long getMissCount()Get the number of cache misses. -
getEvictionCount
long getEvictionCount()Get the number of evictions from the cache. -
getMaxEntries
long getMaxEntries()Get the maximum number of entries in the cache. -
getAllocatedEntries
long getAllocatedEntries()Get the number of allocated entries in the cache. -
getUsedEntries
long getUsedEntries()Get the number of cached objects. -
getSystemModule
-