ehcache

net.sf.ehcache.store
Class MemoryStore

java.lang.Object
  extended by net.sf.ehcache.store.AbstractStore
      extended by 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: MemoryStore.java 9937 2015-09-02 18:48:26Z alexsnaps $
Author:
Terracotta

Nested Class Summary
protected static interface MemoryStore.BackingFactory
          Factory interface to create a MemoryStore backing.
 
Field Summary
protected  org.terracotta.statistics.observer.OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver
          Eviction 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
protected MemoryStore(Ehcache cache, Pool pool, MemoryStore.BackingFactory factory, SearchManager searchManager)
          Constructs things that all MemoryStores have in common.
 
Method Summary
 boolean bufferFull()
          Memory stores are never backed up and always return false
 boolean canPutWithoutEvicting(Element element)
          Check if adding an element won't provoke an eviction.
 boolean containsKey(Object key)
          A check to see if a key is in the Store.
 boolean containsKeyInMemory(Object key)
          A check to see if a key is in the Store and is currently held in memory.
 boolean containsKeyOffHeap(Object key)
          A check to see if a key is in the Store and is currently held off-heap.
 boolean containsKeyOnDisk(Object key)
          A check to see if a key is in the Store and is currently held on disk.
static Store create(Ehcache cache, Pool pool)
          A factory method to create a MemoryStore.
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
 void deregistered(CacheConfiguration config)
          Indicates that this listener was removed from the given configuration
 void diskCapacityChanged(int oldCapacity, int newCapacity)
          Indicates a change in the configurations disk store capacity
 void dispose()
          Prepares for shutdown.
 Collection<Element> elementSet()
          Get a collection of the elements in this store
protected  boolean evict(Element element)
          Evicts the element from the store
protected  Element expireElement(Object key)
          Evicts the element for the given key, if it exists and is expired
 void expireElements()
          Expire all elements.
 void flush()
          Flush to disk only if the cache is diskPersistent.
 Element get(Object key)
          Gets an item from the cache.
protected static int getInitialCapacityForLoadFactor(int maximumSizeGoal, float loadFactor)
          Calculates the initialCapacity for a desired maximumSize goal and loadFactor.
 Policy getInMemoryEvictionPolicy()
          
 int getInMemorySize()
          Returns the current local in-memory store size
 long getInMemorySizeInBytes()
          Gets the size of the in-memory portion of the store, in bytes.
 Object getInternalContext()
          This should not be used, and will generally return null
 List<?> getKeys()
          Gets an Array of the keys for all elements in the memory cache.
 Object getMBean()
          Optional implementation specific MBean exposed by the store.
 int getOffHeapSize()
          Returns the current local off-heap store size
 long getOffHeapSizeInBytes()
          Gets the size of the off-heap portion of the store, in bytes.
 int getOnDiskSize()
          Returns the current local on-disk store size
 long getOnDiskSizeInBytes()
          Gets the size of the on-disk portion of the store, in bytes.
 Element getQuiet(Object key)
          Gets an item from the cache, without updating statistics.
 int getSize()
          Returns the current store size.
 Status getStatus()
          Gets the status of the MemoryStore.
 int getTerracottaClusteredSize()
          Returns nothing since a disk store isn't clustered
 boolean hasAbortedSizeOf()
          Checks if the cache may contain elements for which the SizeOf engine gave up and only partially calculated the size.
 boolean isFull()
          An algorithm to tell if the MemoryStore is at or beyond its carrying capacity.
protected  Set<?> keySet()
          Returns the keySet for this store
 void loggingChanged(boolean oldValue, boolean newValue)
          Indicates a change in the configuration for enable/disable logging
 void maxBytesLocalDiskChanged(long oldValue, long newValue)
          Indicates a change in the configuration for maxBytesLocalDisk setting
 void maxBytesLocalHeapChanged(long oldValue, long newValue)
          Indicates a change in the configuration for maxBytesLocalHeap setting
 void maxEntriesInCacheChanged(long oldValue, long newValue)
          Indicates a change in the configuration for maxEntriesInCache setting
 void memoryCapacityChanged(int oldCapacity, int newCapacity)
          Indicates a change in the configurations memory store capacity
protected  void notifyDirectEviction(Element element)
          Called when an element is evicted even before it could be installed inside the store
 boolean put(Element element)
          Puts an item in the store.
 Element putIfAbsent(Element element)
          Put an element in the store if no element is currently mapped to the elements key.
 boolean putWithWriter(Element element, CacheWriterManager writerManager)
          Puts an item into the store and the cache writer manager in an atomic operation
 void recalculateSize(Object key)
          Recalculate size of the element mapped to the key
 void registered(CacheConfiguration config)
          Indicates that this listener was registered with the given configuration
 Element remove(Object key)
          Removes an Element from the store.
 void removeAll()
          Remove all of the elements from the store.
 Element removeElement(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.
 Element removeWithWriter(Object key, CacheWriterManager writerManager)
          Removes an item from the store and the cache writer manager in an atomic operation.
 Element replace(Element element)
          Replace the cached element only if an Element is currently cached for this key
 boolean replace(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.
 void setAttributeExtractors(Map<String,AttributeExtractor> extractors)
          Inform this store of the configured attribute extractors.
 void setInMemoryEvictionPolicy(Policy policy)
          Sets the eviction policy strategy.
 void timeToIdleChanged(long oldTti, long newTti)
          Indicates a change in the configurations time to idle
 void timeToLiveChanged(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 cache
pool - the pool tracking the on-heap usage
searchManager - 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 goal
loadFactor - 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 cache
pool - 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 source
cacheConfiguration - 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:
put in interface Store
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:
putWithWriter in interface Store
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(Object key)
Gets an item from the cache.

The last access time in Element is updated.

Specified by:
get in interface Store
Parameters:
key - the key of the Element
Returns:
the element, or null if there was no match for the key

getQuiet

public final Element getQuiet(Object key)
Gets an item from the cache, without updating statistics.

Specified by:
getQuiet in interface Store
Parameters:
key - the cache key
Returns:
the element, or null if there was no match for the key

remove

public Element remove(Object key)
Removes an Element from the store.

Specified by:
remove in interface Store
Parameters:
key - the key of the Element, usually a String
Returns:
the Element if one was found, else null

removeWithWriter

public final Element removeWithWriter(Object key,
                                      CacheWriterManager writerManager)
                               throws CacheException
Removes an item from the store and the cache writer manager in an atomic operation.

Specified by:
removeWithWriter in interface Store
Throws:
CacheException

bufferFull

public final boolean bufferFull()
Memory stores are never backed up and always return false

Specified by:
bufferFull in interface Store
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:
expireElements in interface Store

expireElement

protected Element expireElement(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 CacheException
Remove all of the elements from the store.

Specified by:
removeAll in interface Store
Throws:
CacheException

dispose

public void dispose()
Prepares for shutdown.

Specified by:
dispose in interface Store

flush

public void flush()
Flush to disk only if the cache is diskPersistent.

Specified by:
flush in interface Store

getKeys

public final List<?> getKeys()
Gets an Array of the keys for all elements in the memory cache.

Does not check for expired entries

Specified by:
getKeys in interface Store
Returns:
An List

keySet

protected Set<?> keySet()
Returns the keySet for this store

Returns:
keySet

getSize

public final int getSize()
Returns the current store size.

Specified by:
getSize in interface Store
Returns:
The size value

getTerracottaClusteredSize

public final int getTerracottaClusteredSize()
Returns nothing since a disk store isn't clustered

Specified by:
getTerracottaClusteredSize in interface Store
Returns:
returns 0

containsKey

public final boolean containsKey(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:
containsKey in interface Store
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 Object getInternalContext()
This should not be used, and will generally return null

Specified by:
getInternalContext in interface Store
Returns:
some internal context (probably null)

getStatus

public final Status getStatus()
Gets the status of the MemoryStore.

Specified by:
getStatus in interface Store

timeToIdleChanged

public void timeToIdleChanged(long oldTti,
                              long newTti)
Indicates a change in the configurations time to idle

Specified by:
timeToIdleChanged in interface CacheConfigurationListener
Parameters:
oldTti - previous time to idle value
newTti - new time to idle value

timeToLiveChanged

public void timeToLiveChanged(long oldTtl,
                              long newTtl)
Indicates a change in the configurations time to live

Specified by:
timeToLiveChanged in interface CacheConfigurationListener
Parameters:
oldTtl - previous time to live value
newTtl - new time to live value

diskCapacityChanged

public void diskCapacityChanged(int oldCapacity,
                                int newCapacity)
Indicates a change in the configurations disk store capacity

Specified by:
diskCapacityChanged in interface CacheConfigurationListener
Parameters:
oldCapacity - previous capacity
newCapacity - new capacity

loggingChanged

public void loggingChanged(boolean oldValue,
                           boolean newValue)
Indicates a change in the configuration for enable/disable logging

Specified by:
loggingChanged in interface CacheConfigurationListener
Parameters:
oldValue - old value whether logging was enabled or not
newValue - 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:
memoryCapacityChanged in interface CacheConfigurationListener
Parameters:
oldCapacity - previous capacity
newCapacity - new capacity

registered

public void registered(CacheConfiguration config)
Indicates that this listener was registered with the given configuration

Specified by:
registered in interface CacheConfigurationListener

deregistered

public void deregistered(CacheConfiguration config)
Indicates that this listener was removed from the given configuration

Specified by:
deregistered in interface CacheConfigurationListener

maxBytesLocalHeapChanged

public void maxBytesLocalHeapChanged(long oldValue,
                                     long newValue)
Indicates a change in the configuration for maxBytesLocalHeap setting

Specified by:
maxBytesLocalHeapChanged in interface CacheConfigurationListener
Parameters:
oldValue - old value in bytes
newValue - new value in bytes

maxBytesLocalDiskChanged

public void maxBytesLocalDiskChanged(long oldValue,
                                     long newValue)
Indicates a change in the configuration for maxBytesLocalDisk setting

Specified by:
maxBytesLocalDiskChanged in interface CacheConfigurationListener
Parameters:
oldValue - old value in bytes
newValue - new value in bytes

maxEntriesInCacheChanged

public void maxEntriesInCacheChanged(long oldValue,
                                     long newValue)
Indicates a change in the configuration for maxEntriesInCache setting

Specified by:
maxEntriesInCacheChanged in interface CacheConfigurationListener
Parameters:
oldValue - old value
newValue - new value

containsKeyInMemory

public boolean containsKeyInMemory(Object key)
A check to see if a key is in the Store and is currently held in memory.

Specified by:
containsKeyInMemory in interface Store
Parameters:
key - The Element key
Returns:
true if found. No check is made to see if the Element is expired.

containsKeyOffHeap

public boolean containsKeyOffHeap(Object key)
A check to see if a key is in the Store and is currently held off-heap.

Specified by:
containsKeyOffHeap in interface Store
Parameters:
key - The Element key
Returns:
true if found. No check is made to see if the Element is expired.

containsKeyOnDisk

public boolean containsKeyOnDisk(Object key)
A check to see if a key is in the Store and is currently held on disk.

Specified by:
containsKeyOnDisk in interface Store
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:
getInMemoryEvictionPolicy in interface Store
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:
getInMemorySize in interface Store
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:
getInMemorySizeInBytes in interface Store
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:
getOffHeapSize in interface Store
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:
getOffHeapSizeInBytes in interface Store
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:
getOnDiskSize in interface Store
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:
getOnDiskSizeInBytes in interface Store
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:
hasAbortedSizeOf in interface Store
Overrides:
hasAbortedSizeOf in class AbstractStore
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:
setInMemoryEvictionPolicy in interface Store
Parameters:
policy - the new policy

setAttributeExtractors

public void setAttributeExtractors(Map<String,AttributeExtractor> extractors)
Description copied from class: AbstractStore
Inform this store of the configured attribute extractors. Stores that will not invoke extractors are free to ignore this call

Specified by:
setAttributeExtractors in interface Store
Overrides:
setAttributeExtractors in class AbstractStore

putIfAbsent

public Element putIfAbsent(Element element)
                    throws NullPointerException
Put an element in the store if no element is currently mapped to the elements key.

Specified by:
putIfAbsent in interface Store
Parameters:
element - element to be added
Returns:
the element previously cached for this key, or null if none.
Throws:
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

removeElement

public Element removeElement(Element element,
                             ElementValueComparator comparator)
                      throws 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:
removeElement in interface Store
Parameters:
element - Element to be removed
comparator - ElementValueComparator to use to compare elements
Returns:
the Element removed or null if no Element was removed
Throws:
NullPointerException - if the element is null, or has a null key

replace

public boolean replace(Element old,
                       Element element,
                       ElementValueComparator comparator)
                throws NullPointerException,
                       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:
replace in interface Store
Parameters:
old - Element to be test against
element - Element to be cached
comparator - ElementValueComparator to use to compare elements
Returns:
true is the Element was replaced
Throws:
NullPointerException - if the either Element is null or has a null key
IllegalArgumentException - if the two Element keys are non-null but not equal

replace

public Element replace(Element element)
                throws NullPointerException
Replace the cached element only if an Element is currently cached for this key

Specified by:
replace in interface Store
Parameters:
element - Element to be cached
Returns:
the Element previously cached for this key, or null if no Element was cached
Throws:
NullPointerException - if the Element is null or has a null key

getMBean

public Object getMBean()
Optional implementation specific MBean exposed by the store.

Specified by:
getMBean in interface Store
Returns:
implementation specific management bean

elementSet

public Collection<Element> elementSet()
Get a collection of the elements in this store

Returns:
element collection

recalculateSize

public void recalculateSize(Object key)
Description copied from class: AbstractStore
Recalculate size of the element mapped to the key

Specified by:
recalculateSize in interface Store
Overrides:
recalculateSize in class AbstractStore
Parameters:
key - the key

ehcache

Copyright 2001-2017, Terracotta, Inc.