Product Documentation : Ehcache Developer Guide : Basic Caching : Performing Basic Cache Operations
Performing Basic Cache Operations
The following examples refer to manager, which is a reference to a CacheManager that contains a cache called sampleCache1.
Obtaining a reference to a Cache
The following obtains a Cache called sampleCache1, which has been preconfigured in the configuration file
Cache cache = manager.getCache("sampleCache1");
Putting an Element in Cache
The following puts an element into a cache
Cache cache = manager.getCache("sampleCache1");
Element element = new Element("key1", "value1");
cache.put(element);
Updating and Element in Cache
The following updates an element in a cache. Even though cache.put( ) is used, Ehcache knows there is an existing element, and considers the put operation as an update for the purpose of notifying cache listeners.
Cache cache = manager.getCache("sampleCache1");
cache.put(new Element("key1", "value1"));
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));
Getting an Element from Cache
The following gets a Serializable value from an element with a key of key1.
Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Serializable value = element.getValue();
The following gets a NonSerializable value from an element with a key of key1.
Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Object value = element.getObjectValue();
Removing an Element from Cache
The following removes an element with a key of key1.
Cache cache = manager.getCache("sampleCache1");
cache.remove("key1");
Obtaining Cache Sizes
The following gets the number of elements currently in the cache.
Cache cache = manager.getCache("sampleCache1");
int elementsInMemory = cache.getSize();
The following gets the number of elements currently in the MemoryStore.
Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();
The following gets the number of elements currently in the DiskStore.
Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getDiskStoreSize();
Copyright © 2010-2015 Software AG, Darmstadt, Germany.

Product Logo |   Feedback