BigMemory 4.3.10 | Product Documentation | BigMemory Go Developer Guide | Basic Caching | Adding and Removing Caches Programmatically
 
Adding and Removing Caches Programmatically
Adding Caches Programmatically
You are not limited to using caches that are placed in the CacheManager configuration. A new cache based on the default configuration can be added to a CacheManager very simply:
manager.addCache(cacheName);
For example, the following adds a cache called testCache to CacheManager called singletonManager. The cache is configured using defaultCache from the CacheManager configuration.
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
As shown below, you can also create a new cache with a specified configuration and add the cache to a CacheManager. Note that when you create a new cache, it is not usable until it has been added to a CacheManager.
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");
Below is another way to create a new cache with a specified configuration. This example creates a cache called testCache and adds it CacheManager called manager.
//Create a singleton CacheManager using defaults
CacheManager manager = CacheManager.create();
//Create a Cache specifying its configuration.
Cache testCache = new Cache(
new CacheConfiguration("testCache", maxEntriesLocalHeap)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
manager.addCache(testCache);
For a full list of parameters for a new Cache, see the Cache constructor at http://ehcache.org/apidocs/2.10.1/net/sf/ehcache/Cache.html.
Removing Caches Programmatically
The following removes the cache called sampleCache1:
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");