- Home
- User documentation
General topics: - Caching Terms - Caching Concepts - Caching Patterns
- Resources
Ehcache 3.1 added clustering support but this is not yet compatible with cache-through. |
Write-Through Cache
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
final Cache<Long, String> writeThroughCache = cacheManager.createCache("writeThroughCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
.withLoaderWriter(new SampleLoaderWriter<Long, String>(singletonMap(41L, "zero"))) (1)
.build());
assertThat(writeThroughCache.get(41L), is("zero"));
writeThroughCache.put(42L, "one");
assertThat(writeThroughCache.get(42L), equalTo("one"));
cacheManager.close();
1 | If you wish to use a cache in read-through/write-through caching pattern, you’ll have to implement
a CacheLoaderWriter and configure it. |
Write-Behind Cache
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
final Cache<Long, String> writeBehindCache = cacheManager.createCache("writeBehindCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
.withLoaderWriter(new SampleLoaderWriter<Long, String>(singletonMap(41L, "zero"))) (1)
.add(WriteBehindConfigurationBuilder (2)
.newBatchedWriteBehindConfiguration(1, TimeUnit.SECONDS, 3)(3)
.queueSize(3)(4)
.concurrencyLevel(1) (5)
.enableCoalescing()) (6)
.build());
assertThat(writeBehindCache.get(41L), is("zero"));
writeBehindCache.put(42L, "one");
writeBehindCache.put(43L, "two");
writeBehindCache.put(42L, "This goes for the record");
assertThat(writeBehindCache.get(42L), equalTo("This goes for the record"));
cacheManager.close();
1 | A Cache can be used in write-behind pattern as well. You will have to implement a CacheLoaderWriter and configure it. |
2 | Additionally, register a WriteBehindConfiguration on the Cache by using the WriteBehindConfigurationBuilder . |
3 | Here we configure write behind with a batch size of 3 and a max wait time of 1 second. |
4 | We also set the maximum size of the writebehind queue. |
5 | Define the concurrency level of writebehind queue, at a time these many writer threads will update the underlying resource asynchronously. |
6 | Enable the write coalescing behavior, which ensures that only one update per key per batch hits the underlying resource. |