Package net.sf.ehcache.store
Class MemoryStore
- java.lang.Object
-
- net.sf.ehcache.store.AbstractStore
-
- net.sf.ehcache.store.MemoryStore
-
- All Implemented Interfaces:
CacheConfigurationListener,Store
public class MemoryStore extends AbstractStore implements CacheConfigurationListener, Store
A Store implementation suitable for fast, concurrent in memory stores. The policy is determined by that configured in the cache.- Version:
- $Id$
- Author:
- Terracotta
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static interfaceMemoryStore.BackingFactoryFactory interface to create a MemoryStore backing.
-
Field Summary
Fields Modifier and Type Field Description protected org.terracotta.statistics.observer.OperationObserver<CacheOperationOutcomes.EvictionOutcome>evictionObserverEviction outcome observer-
Fields inherited from class net.sf.ehcache.store.AbstractStore
attributeExtractors, searchManager
-
Fields inherited from interface net.sf.ehcache.store.Store
CLUSTER_COHERENT, NODE_COHERENT
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedMemoryStore(Ehcache cache, Pool pool, MemoryStore.BackingFactory factory, SearchManager searchManager)Constructs things that all MemoryStores have in common.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanbufferFull()Memory stores are never backed up and always return falsebooleancanPutWithoutEvicting(Element element)Check if adding an element won't provoke an eviction.booleancontainsKey(java.lang.Object key)A check to see if a key is in the Store.booleancontainsKeyInMemory(java.lang.Object key)A check to see if a key is in the Store and is currently held in memory.booleancontainsKeyOffHeap(java.lang.Object key)A check to see if a key is in the Store and is currently held off-heap.booleancontainsKeyOnDisk(java.lang.Object key)A check to see if a key is in the Store and is currently held on disk.static Storecreate(Ehcache cache, Pool pool)A factory method to create a MemoryStore.protected static net.sf.ehcache.store.BruteForceSourcecreateBruteForceSource(MemoryStore memoryStore, CacheConfiguration cacheConfiguration)Factory method to wrap the MemoryStore into a BruteForceSource, accounting for transactional and copy configurationvoidderegistered(CacheConfiguration config)Indicates that this listener was removed from the given configurationvoiddiskCapacityChanged(int oldCapacity, int newCapacity)Indicates a change in the configurations disk store capacityvoiddispose()Prepares for shutdown.java.util.Collection<Element>elementSet()Get a collection of the elements in this storeprotected booleanevict(Element element)Evicts the element from the storeprotected booleanexpire(Element element)Evicts the element from the storeprotected ElementexpireElement(java.lang.Object key)Evicts the element for the given key, if it exists and is expiredvoidexpireElements()Expire all elements.voidflush()Flush to disk only if the cache is diskPersistent.Elementget(java.lang.Object key)Gets an item from the cache.protected static intgetInitialCapacityForLoadFactor(int maximumSizeGoal, float loadFactor)Calculates the initialCapacity for a desired maximumSize goal and loadFactor.PolicygetInMemoryEvictionPolicy()intgetInMemorySize()Returns the current local in-memory store sizelonggetInMemorySizeInBytes()Gets the size of the in-memory portion of the store, in bytes.java.lang.ObjectgetInternalContext()This should not be used, and will generally return nulljava.util.List<?>getKeys()Gets an Array of the keys for all elements in the memory cache.java.lang.ObjectgetMBean()Optional implementation specific MBean exposed by the store.intgetOffHeapSize()Returns the current local off-heap store sizelonggetOffHeapSizeInBytes()Gets the size of the off-heap portion of the store, in bytes.intgetOnDiskSize()Returns the current local on-disk store sizelonggetOnDiskSizeInBytes()Gets the size of the on-disk portion of the store, in bytes.ElementgetQuiet(java.lang.Object key)Gets an item from the cache, without updating statistics.intgetSize()Returns the current store size.StatusgetStatus()Gets the status of the MemoryStore.intgetTerracottaClusteredSize()Returns nothing since a disk store isn't clusteredbooleanhasAbortedSizeOf()Checks if the cache may contain elements for which the SizeOf engine gave up and only partially calculated the size.booleanisFull()An algorithm to tell if the MemoryStore is at or beyond its carrying capacity.protected java.util.Set<?>keySet()Returns the keySet for this storevoidloggingChanged(boolean oldValue, boolean newValue)Indicates a change in the configuration for enable/disable loggingvoidmaxBytesLocalDiskChanged(long oldValue, long newValue)Indicates a change in the configuration for maxBytesLocalDisk settingvoidmaxBytesLocalHeapChanged(long oldValue, long newValue)Indicates a change in the configuration for maxBytesLocalHeap settingvoidmaxEntriesInCacheChanged(long oldValue, long newValue)Indicates a change in the configuration for maxEntriesInCache settingvoidmemoryCapacityChanged(int oldCapacity, int newCapacity)Indicates a change in the configurations memory store capacityprotected voidnotifyDirectEviction(Element element)Called when an element is evicted even before it could be installed inside the storebooleanput(Element element)Puts an item in the store.ElementputIfAbsent(Element element)Put an element in the store if no element is currently mapped to the elements key.booleanputWithWriter(Element element, CacheWriterManager writerManager)Puts an item into the store and the cache writer manager in an atomic operationvoidrecalculateSize(java.lang.Object key)Recalculate size of the element mapped to the keyvoidregistered(CacheConfiguration config)Indicates that this listener was registered with the given configurationElementremove(java.lang.Object key)Removes an Element from the store.voidremoveAll()Remove all of the elements from the store.ElementremoveElement(Element element, ElementValueComparator comparator)Remove the Element mapped to the key for the supplied element if the value of the supplied Element is equal to the value of the cached Element.ElementremoveWithWriter(java.lang.Object key, CacheWriterManager writerManager)Removes an item from the store and the cache writer manager in an atomic operation.Elementreplace(Element element)Replace the cached element only if an Element is currently cached for this keybooleanreplace(Element old, Element element, ElementValueComparator comparator)Replace the cached element only if the value of the current Element is equal to the value of the supplied old Element.voidsetAttributeExtractors(java.util.Map<java.lang.String,AttributeExtractor> extractors)Inform this store of the configured attribute extractors.voidsetInMemoryEvictionPolicy(Policy policy)Sets the eviction policy strategy.voidtimeToIdleChanged(long oldTti, long newTti)Indicates a change in the configurations time to idlevoidtimeToLiveChanged(long oldTtl, long newTtl)Indicates a change in the configurations time to live-
Methods inherited from class net.sf.ehcache.store.AbstractStore
addStoreListener, executeQuery, getAll, getAllQuiet, getEventListenerList, getSearchAttribute, getSearchAttributes, isCacheCoherent, isClusterCoherent, isNodeCoherent, putAll, removeAll, removeStoreListener, setNodeCoherent, waitUntilClusterCoherent
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface net.sf.ehcache.store.Store
addStoreListener, executeQuery, getAll, getAllQuiet, getSearchAttribute, getSearchAttributes, isCacheCoherent, isClusterCoherent, isNodeCoherent, putAll, removeAll, removeStoreListener, setNodeCoherent, waitUntilClusterCoherent
-
-
-
-
Field Detail
-
evictionObserver
protected final org.terracotta.statistics.observer.OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver
Eviction outcome observer
-
-
Constructor Detail
-
MemoryStore
protected MemoryStore(Ehcache cache, Pool pool, MemoryStore.BackingFactory factory, SearchManager searchManager)
Constructs things that all MemoryStores have in common.- Parameters:
cache- the cachepool- the pool tracking the on-heap usagesearchManager- the search manager
-
-
Method Detail
-
getInitialCapacityForLoadFactor
protected static int getInitialCapacityForLoadFactor(int maximumSizeGoal, float loadFactor)Calculates the initialCapacity for a desired maximumSize goal and loadFactor.- Parameters:
maximumSizeGoal- the desired maximum size goalloadFactor- the load factor- Returns:
- the calculated initialCapacity. Returns 0 if the parameter maximumSizeGoal is less than or equal to 0
-
create
public static Store create(Ehcache cache, Pool pool)
A factory method to create a MemoryStore.- Parameters:
cache- the cachepool- the pool tracking the on-heap usage- Returns:
- an instance of a NotifyingMemoryStore, configured with the appropriate eviction policy
-
createBruteForceSource
protected static net.sf.ehcache.store.BruteForceSource createBruteForceSource(MemoryStore memoryStore, CacheConfiguration cacheConfiguration)
Factory method to wrap the MemoryStore into a BruteForceSource, accounting for transactional and copy configuration- Parameters:
memoryStore- the underlying store acting as sourcecacheConfiguration- the cache configuration- Returns:
- a BruteForceSource connected to underlying MemoryStore and matching configuration
-
put
public boolean put(Element element) throws CacheException
Puts an item in the store. Note that this automatically results in an eviction if the store is full.- Specified by:
putin interfaceStore- Parameters:
element- the element to add- Returns:
- true if this is a new put for the key or element is null. Returns false if it was an update.
- Throws:
CacheException
-
putWithWriter
public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException
Puts an item into the store and the cache writer manager in an atomic operation- Specified by:
putWithWriterin interfaceStore- Returns:
- true if this is a new put for the key or element is null. Returns false if it was an update.
- Throws:
CacheException
-
get
public final Element get(java.lang.Object key)
Gets an item from the cache.The last access time in
Elementis updated.
-
getQuiet
public final Element getQuiet(java.lang.Object key)
Gets an item from the cache, without updating statistics.
-
remove
public Element remove(java.lang.Object key)
Removes an Element from the store.
-
removeWithWriter
public final Element removeWithWriter(java.lang.Object key, CacheWriterManager writerManager) throws CacheException
Removes an item from the store and the cache writer manager in an atomic operation.- Specified by:
removeWithWriterin interfaceStore- Throws:
CacheException
-
bufferFull
public final boolean bufferFull()
Memory stores are never backed up and always return false- Specified by:
bufferFullin interfaceStore- Returns:
- true if the store write buffer is backed up.
-
expireElements
public void expireElements()
Expire all elements.This is a default implementation which does nothing. Expiration on demand is only implemented for disk stores.
- Specified by:
expireElementsin interfaceStore
-
expireElement
protected Element expireElement(java.lang.Object key)
Evicts the element for the given key, if it exists and is expired- Parameters:
key- the key- Returns:
- the evicted element, if any. Otherwise null
-
removeAll
public final void removeAll() throws CacheExceptionRemove all of the elements from the store.- Specified by:
removeAllin interfaceStore- Throws:
CacheException
-
flush
public void flush()
Flush to disk only if the cache is diskPersistent.
-
getKeys
public final java.util.List<?> getKeys()
Gets an Array of the keys for all elements in the memory cache.Does not check for expired entries
-
keySet
protected java.util.Set<?> keySet()
Returns the keySet for this store- Returns:
- keySet
-
getSize
public final int getSize()
Returns the current store size.
-
getTerracottaClusteredSize
public final int getTerracottaClusteredSize()
Returns nothing since a disk store isn't clustered- Specified by:
getTerracottaClusteredSizein interfaceStore- Returns:
- returns 0
-
containsKey
public final boolean containsKey(java.lang.Object key)
A check to see if a key is in the Store. No check is made to see if the Element is expired.- Specified by:
containsKeyin interfaceStore- Parameters:
key- The Element key- Returns:
- true if found. If this method return false, it means that an Element with the given key is definitely not in the MemoryStore. If it returns true, there is an Element there. An attempt to get it may return null if the Element has expired.
-
notifyDirectEviction
protected void notifyDirectEviction(Element element)
Called when an element is evicted even before it could be installed inside the store- Parameters:
element- the evicted element
-
isFull
public final boolean isFull()
An algorithm to tell if the MemoryStore is at or beyond its carrying capacity.- Returns:
- true if the store is full, false otherwise
-
canPutWithoutEvicting
public final boolean canPutWithoutEvicting(Element element)
Check if adding an element won't provoke an eviction.- Parameters:
element- the element- Returns:
- true if the element can be added without provoking an eviction.
-
getInternalContext
public java.lang.Object getInternalContext()
This should not be used, and will generally return null- Specified by:
getInternalContextin interfaceStore- Returns:
- some internal context (probably null)
-
getStatus
public final Status getStatus()
Gets the status of the MemoryStore.
-
timeToIdleChanged
public void timeToIdleChanged(long oldTti, long newTti)Indicates a change in the configurations time to idle- Specified by:
timeToIdleChangedin interfaceCacheConfigurationListener- Parameters:
oldTti- previous time to idle valuenewTti- new time to idle value
-
timeToLiveChanged
public void timeToLiveChanged(long oldTtl, long newTtl)Indicates a change in the configurations time to live- Specified by:
timeToLiveChangedin interfaceCacheConfigurationListener- Parameters:
oldTtl- previous time to live valuenewTtl- new time to live value
-
diskCapacityChanged
public void diskCapacityChanged(int oldCapacity, int newCapacity)Indicates a change in the configurations disk store capacity- Specified by:
diskCapacityChangedin interfaceCacheConfigurationListener- Parameters:
oldCapacity- previous capacitynewCapacity- new capacity
-
loggingChanged
public void loggingChanged(boolean oldValue, boolean newValue)Indicates a change in the configuration for enable/disable logging- Specified by:
loggingChangedin interfaceCacheConfigurationListener- Parameters:
oldValue- old value whether logging was enabled or notnewValue- new value whether logging was enabled or not
-
memoryCapacityChanged
public void memoryCapacityChanged(int oldCapacity, int newCapacity)Indicates a change in the configurations memory store capacity- Specified by:
memoryCapacityChangedin interfaceCacheConfigurationListener- Parameters:
oldCapacity- previous capacitynewCapacity- new capacity
-
registered
public void registered(CacheConfiguration config)
Indicates that this listener was registered with the given configuration- Specified by:
registeredin interfaceCacheConfigurationListener
-
deregistered
public void deregistered(CacheConfiguration config)
Indicates that this listener was removed from the given configuration- Specified by:
deregisteredin interfaceCacheConfigurationListener
-
maxBytesLocalHeapChanged
public void maxBytesLocalHeapChanged(long oldValue, long newValue)Indicates a change in the configuration for maxBytesLocalHeap setting- Specified by:
maxBytesLocalHeapChangedin interfaceCacheConfigurationListener- Parameters:
oldValue- old value in bytesnewValue- new value in bytes
-
maxBytesLocalDiskChanged
public void maxBytesLocalDiskChanged(long oldValue, long newValue)Indicates a change in the configuration for maxBytesLocalDisk setting- Specified by:
maxBytesLocalDiskChangedin interfaceCacheConfigurationListener- Parameters:
oldValue- old value in bytesnewValue- new value in bytes
-
maxEntriesInCacheChanged
public void maxEntriesInCacheChanged(long oldValue, long newValue)Indicates a change in the configuration for maxEntriesInCache setting- Specified by:
maxEntriesInCacheChangedin interfaceCacheConfigurationListener- Parameters:
oldValue- old valuenewValue- new value
-
containsKeyInMemory
public boolean containsKeyInMemory(java.lang.Object key)
A check to see if a key is in the Store and is currently held in memory.- Specified by:
containsKeyInMemoryin interfaceStore- Parameters:
key- The Element key- Returns:
- true if found. No check is made to see if the Element is expired.
-
containsKeyOffHeap
public boolean containsKeyOffHeap(java.lang.Object key)
A check to see if a key is in the Store and is currently held off-heap.- Specified by:
containsKeyOffHeapin interfaceStore- Parameters:
key- The Element key- Returns:
- true if found. No check is made to see if the Element is expired.
-
containsKeyOnDisk
public boolean containsKeyOnDisk(java.lang.Object key)
A check to see if a key is in the Store and is currently held on disk.- Specified by:
containsKeyOnDiskin interfaceStore- Parameters:
key- The Element key- Returns:
- true if found. No check is made to see if the Element is expired.
-
getInMemoryEvictionPolicy
public Policy getInMemoryEvictionPolicy()
- Specified by:
getInMemoryEvictionPolicyin interfaceStore- Returns:
- the current eviction policy. This may not be the configured policy, if it has been dynamically set.
- See Also:
Store.setInMemoryEvictionPolicy(Policy)
-
getInMemorySize
public int getInMemorySize()
Returns the current local in-memory store size- Specified by:
getInMemorySizein interfaceStore- Returns:
- the count of the Elements in the Store and in-memory on the local machine
-
getInMemorySizeInBytes
public long getInMemorySizeInBytes()
Gets the size of the in-memory portion of the store, in bytes.This method may be expensive to run, depending on implementation. Implementers may choose to return an approximate size.
- Specified by:
getInMemorySizeInBytesin interfaceStore- Returns:
- the approximate in-memory size of the store in bytes
-
getOffHeapSize
public int getOffHeapSize()
Returns the current local off-heap store size- Specified by:
getOffHeapSizein interfaceStore- Returns:
- the count of the Elements in the Store and off-heap on the local machine
-
getOffHeapSizeInBytes
public long getOffHeapSizeInBytes()
Gets the size of the off-heap portion of the store, in bytes.- Specified by:
getOffHeapSizeInBytesin interfaceStore- Returns:
- the approximate off-heap size of the store in bytes
-
getOnDiskSize
public int getOnDiskSize()
Returns the current local on-disk store size- Specified by:
getOnDiskSizein interfaceStore- Returns:
- the count of the Elements in the Store and on-disk on the local machine
-
getOnDiskSizeInBytes
public long getOnDiskSizeInBytes()
Gets the size of the on-disk portion of the store, in bytes.- Specified by:
getOnDiskSizeInBytesin interfaceStore- Returns:
- the on-disk size of the store in bytes
-
hasAbortedSizeOf
public boolean hasAbortedSizeOf()
Checks if the cache may contain elements for which the SizeOf engine gave up and only partially calculated the size.- Specified by:
hasAbortedSizeOfin interfaceStore- Overrides:
hasAbortedSizeOfin classAbstractStore- Returns:
- true if at least one partially sized element may be in the cache
-
setInMemoryEvictionPolicy
public void setInMemoryEvictionPolicy(Policy policy)
Sets the eviction policy strategy. The Store will use a policy at startup. The store may allow changing the eviction policy strategy dynamically. Otherwise implementations will throw an exception if this method is called.- Specified by:
setInMemoryEvictionPolicyin interfaceStore- Parameters:
policy- the new policy
-
setAttributeExtractors
public void setAttributeExtractors(java.util.Map<java.lang.String,AttributeExtractor> extractors)
Description copied from class:AbstractStoreInform this store of the configured attribute extractors. Stores that will not invoke extractors are free to ignore this call- Specified by:
setAttributeExtractorsin interfaceStore- Overrides:
setAttributeExtractorsin classAbstractStore
-
putIfAbsent
public Element putIfAbsent(Element element) throws java.lang.NullPointerException
Put an element in the store if no element is currently mapped to the elements key.- Specified by:
putIfAbsentin interfaceStore- Parameters:
element- element to be added- Returns:
- the element previously cached for this key, or null if none.
- Throws:
java.lang.NullPointerException- if the element is null, or has a null key
-
evict
protected boolean evict(Element element)
Evicts the element from the store- Parameters:
element- the element to be evicted- Returns:
- true if succeeded, false otherwise
-
expire
protected boolean expire(Element element)
Evicts the element from the store- Parameters:
element- the element to be evicted- Returns:
- true if succeeded, false otherwise
-
removeElement
public Element removeElement(Element element, ElementValueComparator comparator) throws java.lang.NullPointerException
Remove the Element mapped to the key for the supplied element if the value of the supplied Element is equal to the value of the cached Element. This is a CAS operation. It is consistent even against a distributed cache that is not coherent. If the old value is stale when this operation is attempted the remove does not take place.- Specified by:
removeElementin interfaceStore- Parameters:
element- Element to be removedcomparator- ElementValueComparator to use to compare elements- Returns:
- the Element removed or null if no Element was removed
- Throws:
java.lang.NullPointerException- if the element is null, or has a null key
-
replace
public boolean replace(Element old, Element element, ElementValueComparator comparator) throws java.lang.NullPointerException, java.lang.IllegalArgumentException
Replace the cached element only if the value of the current Element is equal to the value of the supplied old Element.- Specified by:
replacein interfaceStore- Parameters:
old- Element to be test againstelement- Element to be cachedcomparator- ElementValueComparator to use to compare elements- Returns:
- true is the Element was replaced
- Throws:
java.lang.NullPointerException- if the either Element is null or has a null keyjava.lang.IllegalArgumentException- if the two Element keys are non-null but not equal
-
replace
public Element replace(Element element) throws java.lang.NullPointerException
Replace the cached element only if an Element is currently cached for this key
-
getMBean
public java.lang.Object getMBean()
Optional implementation specific MBean exposed by the store.
-
elementSet
public java.util.Collection<Element> elementSet()
Get a collection of the elements in this store- Returns:
- element collection
-
recalculateSize
public void recalculateSize(java.lang.Object key)
Description copied from class:AbstractStoreRecalculate size of the element mapped to the key- Specified by:
recalculateSizein interfaceStore- Overrides:
recalculateSizein classAbstractStore- Parameters:
key- the key
-
-