package org.apache.commons.jcs3.engine.control; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.jcs3.access.exception.CacheException; import org.apache.commons.jcs3.access.exception.ObjectNotFoundException; import org.apache.commons.jcs3.auxiliary.AuxiliaryCache; import org.apache.commons.jcs3.engine.CacheStatus; import org.apache.commons.jcs3.engine.behavior.ICache; import org.apache.commons.jcs3.engine.behavior.ICacheElement; import org.apache.commons.jcs3.engine.behavior.ICompositeCacheAttributes; import org.apache.commons.jcs3.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern; import org.apache.commons.jcs3.engine.behavior.IElementAttributes; import org.apache.commons.jcs3.engine.behavior.IRequireScheduler; import org.apache.commons.jcs3.engine.control.event.ElementEvent; import org.apache.commons.jcs3.engine.control.event.behavior.ElementEventType; import org.apache.commons.jcs3.engine.control.event.behavior.IElementEvent; import org.apache.commons.jcs3.engine.control.event.behavior.IElementEventHandler; import org.apache.commons.jcs3.engine.control.event.behavior.IElementEventQueue; import org.apache.commons.jcs3.engine.control.group.GroupId; import org.apache.commons.jcs3.engine.match.KeyMatcherPatternImpl; import org.apache.commons.jcs3.engine.match.behavior.IKeyMatcher; import org.apache.commons.jcs3.engine.memory.behavior.IMemoryCache; import org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache; import org.apache.commons.jcs3.engine.memory.shrinking.ShrinkerThread; import org.apache.commons.jcs3.engine.stats.CacheStats; import org.apache.commons.jcs3.engine.stats.StatElement; import org.apache.commons.jcs3.engine.stats.behavior.ICacheStats; import org.apache.commons.jcs3.engine.stats.behavior.IStats; import org.apache.commons.jcs3.log.Log; import org.apache.commons.jcs3.log.LogManager; /** * This is the primary hub for a single cache/region. It controls the flow of items through the * cache. The auxiliary and memory caches are plugged in here. *
* This is the core of a JCS region. Hence, this simple class is the core of JCS.
*/
public class CompositeCache
* @param cattr The cache attribute
* @param attr The default element attributes
*/
public CompositeCache(final ICompositeCacheAttributes cattr, final IElementAttributes attr)
{
this.attr = attr;
this.cacheAttr = cattr;
this.alive = new AtomicBoolean(true);
this.updateCount = new AtomicLong();
this.removeCount = new AtomicLong();
this.hitCountRam = new AtomicLong();
this.hitCountAux = new AtomicLong();
this.missCountNotFound = new AtomicLong();
this.missCountExpired = new AtomicLong();
createMemoryCache(cattr);
log.info("Constructed cache with name [{0}] and cache attributes {1}",
cacheAttr.getCacheName(), cattr);
}
/**
* Injector for Element event queue
*
* @param queue
*/
public void setElementEventQueue(final IElementEventQueue queue)
{
this.elementEventQ = queue;
}
/**
* Injector for cache manager
*
* @param manager
*/
public void setCompositeCacheManager(final CompositeCacheManager manager)
{
this.cacheManager = manager;
}
/**
* @see org.apache.commons.jcs3.engine.behavior.IRequireScheduler#setScheduledExecutorService(java.util.concurrent.ScheduledExecutorService)
*/
@Override
public void setScheduledExecutorService(final ScheduledExecutorService scheduledExecutor)
{
if (cacheAttr.isUseMemoryShrinker())
{
future = scheduledExecutor.scheduleAtFixedRate(
new ShrinkerThread<>(this), 0, cacheAttr.getShrinkerIntervalSeconds(),
TimeUnit.SECONDS);
}
if (memCache instanceof IRequireScheduler)
{
((IRequireScheduler) memCache).setScheduledExecutorService(scheduledExecutor);
}
}
/**
* This sets the list of auxiliary caches for this region.
* It filters out null caches
*
* @param auxCaches
* @since 3.1
*/
public void setAuxCaches(final List
* @param auxCaches
* @deprecated Use List method
*/
@Deprecated
public void setAuxCaches(final AuxiliaryCache
* @return a list of auxiliary caches, may be empty, never null
* @since 3.1
*/
public List
* @return an array of auxiliary caches, may be empty, never null
* @deprecated Use List method
*/
@SuppressWarnings("unchecked") // No generic arrays in Java
@Deprecated
public AuxiliaryCache
* @param ce
* @throws IOException
*/
@Override
public void update(final ICacheElement
* @param ce
* @throws IOException
*/
public void localUpdate(final ICacheElement
* @param cacheElement the ICacheElement<K, V>
* @param localOnly Whether the operation should be restricted to local auxiliaries.
* @throws IOException
*/
protected void update(final ICacheElement
* Before updating an auxiliary it checks to see if the element attributes permit the operation.
*
* Disk auxiliaries are only updated if the disk cache is not merely used as a swap. If the disk
* cache is merely a swap, then items will only go to disk when they overflow from memory.
*
* This is called by update(cacheElement, localOnly) after it updates the memory cache.
*
* This is protected to make it testable.
*
* @param cacheElement
* @param localOnly
* @throws IOException
*/
protected void updateAuxiliaries(final ICacheElement
* If JCS is not configured to use the disk as a swap, that is if the
* CompositeCacheAttribute diskUsagePattern is not SWAP_ONLY, then the item will not be spooled.
*
* @param ce The CacheElement
*/
public void spoolToDisk(final ICacheElement
* @param key
* @return element from the cache, or null if not present
* @see org.apache.commons.jcs3.engine.behavior.ICache#get(Object)
*/
@Override
public ICacheElement
* @param key
* @return ICacheElement
*/
public ICacheElement
* Do not try to go remote or laterally for this get if it is localOnly. Otherwise try to go
* remote or lateral if such an auxiliary is configured for this region.
*
* @param key
* @param localOnly
* @return ICacheElement
*/
protected ICacheElement
* @param keys
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any of these keys
*/
@Override
public Map
* @param keys
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any of these keys
*/
public Map
* Do not try to go remote or laterally for this get if it is localOnly. Otherwise try to go
* remote or lateral if such an auxiliary is configured for this region.
*
* @param keys
* @param localOnly
* @return ICacheElement
*/
protected Map
* @param keys
* @return the elements found in the memory cache
* @throws IOException
*/
private Map
* @param keys
* @param localOnly
* @return the elements found in the auxiliary caches
* @throws IOException
*/
private Map
* @param pattern
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any matching keys
*/
@Override
public Map
* @param pattern
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any matching keys
*/
public Map
* Do not try to go remote or laterally for this get if it is localOnly. Otherwise try to go
* remote or lateral if such an auxiliary is configured for this region.
*
* @param pattern
* @param localOnly
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any matching keys
*/
protected Map
* @param pattern
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any matching keys
* @throws IOException
*/
protected Map
* Moves in reverse order of definition. This will allow you to override those that are from the
* remote with those on disk.
*
* @param pattern
* @param localOnly
* @return a map of K key to ICacheElement<K, V> element, or an empty map if there is no
* data in cache for any matching keys
* @throws IOException
*/
private Map
* @param aux the auxiliary cache instance
* @param elementsFromAuxiliary
* @throws IOException
*/
private void processRetrievedElements(final AuxiliaryCache
* @param element
* @throws IOException
*/
private void copyAuxiliaryRetrievedItemToMemory(final ICacheElement
* @param keys
* @param foundElements
* @return the original set of cache keys, minus any cache keys present in the map keys of the
* foundElements map
*/
private Set
* @return A set of the key type
*/
public Set
* @param localOnly true if only memory keys are requested
*
* @return A set of the key type
*/
public Set
* @param key
* @return true is it was removed
* @see org.apache.commons.jcs3.engine.behavior.ICache#remove(Object)
*/
@Override
public boolean remove(final K key)
{
return remove(key, false);
}
/**
* Do not propagate removeall laterally or remotely.
*
* @param key
* @return true if the item was already in the cache.
*/
public boolean localRemove(final K key)
{
return remove(key, true);
}
/**
* fromRemote: If a remove call was made on a cache with both, then the remote should have been
* called. If it wasn't then the remote is down. we'll assume it is down for all. If it did come
* from the remote then the cache is remotely configured and lateral removal is unnecessary. If
* it came laterally then lateral removal is unnecessary. Does this assume that there is only
* one lateral and remote for the cache? Not really, the initial removal should take care of the
* problem if the source cache was similarly configured. Otherwise the remote cache, if it had
* no laterals, would remove all the elements from remotely configured caches, but if those
* caches had some other weird laterals that were not remotely configured, only laterally
* propagated then they would go out of synch. The same could happen for multiple remotes. If
* this looks necessary we will need to build in an identifier to specify the source of a
* removal.
*
* @param key
* @param localOnly
* @return true if the item was in the cache, else false
*/
protected boolean remove(final K key, final boolean localOnly)
{
removeCount.incrementAndGet();
boolean removed = false;
try
{
removed = memCache.remove(key);
}
catch (final IOException e)
{
log.error(e);
}
// Removes from all auxiliary caches.
for (final ICache
* @see org.apache.commons.jcs3.engine.behavior.ICache#removeAll()
*/
@Override
public void removeAll()
throws IOException
{
removeAll(false);
}
/**
* Will not pass the remove message remotely.
*
* @throws IOException
*/
public void localRemoveAll()
throws IOException
{
removeAll(true);
}
/**
* Removes all cached items.
*
* @param localOnly must pass in false to get remote and lateral aux's updated. This prevents
* looping.
* @throws IOException
*/
protected void removeAll(final boolean localOnly)
throws IOException
{
try
{
memCache.removeAll();
log.debug("Removed All keys from the memory cache.");
}
catch (final IOException ex)
{
log.error("Trouble updating memory cache.", ex);
}
// Removes from all auxiliary disk caches.
auxCaches.stream()
.filter(aux -> aux.getCacheType() == CacheType.DISK_CACHE || !localOnly)
.forEach(aux -> {
try
{
log.debug("Removing All keys from cacheType {0}",
aux::getCacheType);
aux.removeAll();
}
catch (final IOException ex)
{
log.error("Failure removing all from aux " + aux, ex);
}
});
}
/**
* Flushes all cache items from memory to auxiliary caches and close the auxiliary caches.
*/
@Override
public void dispose()
{
dispose(false);
}
/**
* Invoked only by CacheManager. This method disposes of the auxiliaries one by one. For the
* disk cache, the items in memory are freed, meaning that they will be sent through the
* overflow channel to disk. After the auxiliaries are disposed, the memory cache is disposed.
*
* @param fromRemote
*/
public void dispose(final boolean fromRemote)
{
// If already disposed, return immediately
if (!alive.compareAndSet(true, false))
{
return;
}
log.info("In DISPOSE, [{0}] fromRemote [{1}]",
this.cacheAttr::getCacheName, () -> fromRemote);
// Remove us from the cache managers list
// This will call us back but exit immediately
if (cacheManager != null)
{
cacheManager.freeCache(getCacheName(), fromRemote);
}
// Try to stop shrinker thread
if (future != null)
{
future.cancel(true);
}
// Now, shut down the event queue
if (elementEventQ != null)
{
elementEventQ.dispose();
elementEventQ = null;
}
// Dispose of each auxiliary cache, Remote auxiliaries will be
// skipped if 'fromRemote' is true.
for (final ICache
* @return The size value
*/
@Override
public int getSize()
{
return memCache.getSize();
}
/**
* Gets the cacheType attribute of the Cache object.
*
* @return The cacheType value
*/
@Override
public CacheType getCacheType()
{
return CacheType.CACHE_HUB;
}
/**
* Gets the status attribute of the Cache object.
*
* @return The status value
*/
@Override
public CacheStatus getStatus()
{
return alive.get() ? CacheStatus.ALIVE : CacheStatus.DISPOSED;
}
/**
* Gets stats for debugging.
*
* @return String
*/
@Override
public String getStats()
{
return getStatistics().toString();
}
/**
* This returns data gathered for this region and all the auxiliaries it currently uses.
*
* @return Statistics and Info on the Region.
*/
public ICacheStats getStatistics()
{
final ICacheStats stats = new CacheStats();
stats.setRegionName(this.getCacheName());
// store the composite cache stats first
stats.setStatElements(Arrays.asList(
new StatElement<>("HitCountRam", Long.valueOf(getHitCountRam())),
new StatElement<>("HitCountAux", Long.valueOf(getHitCountAux()))));
// memory + aux, memory is not considered an auxiliary internally
final ArrayList
* @return The cacheName value
*/
@Override
public String getCacheName()
{
return cacheAttr.getCacheName();
}
/**
* Gets the default element attribute of the Cache object This returns a copy. It does not
* return a reference to the attributes.
*
* @return The attributes value
*/
public IElementAttributes getElementAttributes()
{
if (attr != null)
{
return attr.clone();
}
return null;
}
/**
* Sets the default element attribute of the Cache object.
*
* @param attr
*/
public void setElementAttributes(final IElementAttributes attr)
{
this.attr = attr;
}
/**
* Gets the ICompositeCacheAttributes attribute of the Cache object.
*
* @return The ICompositeCacheAttributes value
*/
public ICompositeCacheAttributes getCacheAttributes()
{
return this.cacheAttr;
}
/**
* Sets the ICompositeCacheAttributes attribute of the Cache object.
*
* @param cattr The new ICompositeCacheAttributes value
*/
public void setCacheAttributes(final ICompositeCacheAttributes cattr)
{
this.cacheAttr = cattr;
// need a better way to do this, what if it is in error
this.memCache.initialize(this);
}
/**
* Gets the elementAttributes attribute of the Cache object.
*
* @param key
* @return The elementAttributes value
* @throws CacheException
* @throws IOException
*/
public IElementAttributes getElementAttributes(final K key)
throws CacheException, IOException
{
final ICacheElement
* This does not call handle directly; instead the handler and the event are put into a queue.
* This prevents the event handling from blocking normal cache operations.
*
* @param element the item
* @param eventType the event type
*/
public void handleElementEvent(final ICacheElement
* @param cattr
*/
private void createMemoryCache(final ICompositeCacheAttributes cattr)
{
if (memCache == null)
{
try
{
final Class> c = Class.forName(cattr.getMemoryCacheName());
@SuppressWarnings("unchecked") // Need cast
final
IMemoryCache
* @return the MemoryCache implementation
*/
public IMemoryCache
* @return number of hits in memory
*/
public long getHitCountRam()
{
return hitCountRam.get();
}
/**
* Number of times a requested item was found in and auxiliary cache.
* @return number of auxiliary hits.
*/
public long getHitCountAux()
{
return hitCountAux.get();
}
/**
* Number of times a requested element was not found.
* @return number of misses.
*/
public long getMissCountNotFound()
{
return missCountNotFound.get();
}
/**
* Number of times a requested element was found but was expired.
* @return number of found but expired gets.
*/
public long getMissCountExpired()
{
return missCountExpired.get();
}
/**
* @return Returns the updateCount.
*/
public long getUpdateCount()
{
return updateCount.get();
}
/**
* Sets the key matcher used by get matching.
*
* @param keyMatcher
*/
@Override
public void setKeyMatcher(final IKeyMatcher
* @return keyMatcher
*/
public IKeyMatcher
* @return getStats()
*/
@Override
public String toString()
{
return getStats();
}
}