Implementing Cache-Through
CacheManager cacheManager =
CacheManagerBuilder.newCacheManagerBuilder().build(true);
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")); // <2>
writeThroughCache.put(42L, "one"); // <3>
assertThat(writeThroughCache.get(42L), equalTo("one"));
cacheManager.close();
1 | We register a sample CacheLoaderWriter that knows about the mapping ("41L" maps to "zero") . |
2 | Since the cache has no content yet, this will delegate to the CacheLoaderWriter. The returned mapping will populate the cache and be returned to the caller. |
3 | While creating this cache mapping, the CacheLoaderWriter will be invoked to write the mapping into the system of record. |
Adding Write-Behind
CacheManager cacheManager =
CacheManagerBuilder.newCacheManagerBuilder().build(true);
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 | For write-behind you need a configured CacheLoaderWriter. |
2 | Additionally, register a WriteBehindConfiguration on the cache by using the WriteBehindConfigurationBuilder. |
3 | Here we configure write behind or batching with a batch size of 3 and a maximum write delay of 1 second. |
4 | We also set the maximum size of the write-behind queue. |
5 | Define the concurrency level of write-behind queue(s). This indicates how many writer threads work in parallel to update the underlying system of record asynchronously. |
6 | Enable the write coalescing behavior, which ensures that only one update per key per batch reaches the underlying system of record. |