Preventing Mutation on Cached Object: EhCache

I'm implementing the EhCache for caching purpose in one of the projects that I've been working on.

Issue

EhCache implementation was working super awesomely before I came up with the requirement that the object needs modification after retrieving from the cache. In fact, in general, it is good practice not to mutate a value after handing over the object reference to the cache (or anybody else beyond your control). Thanks to @curtfex for this statement on the question that I've posted on StackOverflow.

So, to address the issue, I've to look into the way to copy the object before using it while using the cache to store the value and accessing it with direct object references.

 

Analysis

There are cloning techniques to make a copy of the object ( deep clone and shallow clone). The shallow clone didn't work for me because it copies the reference in case if the field is a reference to another object. The deep clone is expensive because it creates a new copy of object instead of copying the reference.

So, I was looking something within caching framework that provides the copy of cached object so that mutation on that object is possible without affecting the original object.

I found out that EhCache3 has Serializers and Copiers protecting the cached object from modification by providing the copy of the actual object.

Before this, I was using EhCache 2.

 

Implementation

I've included the example that I created while working around with this issue in my Github repository. ehcache package contains code with EhCache2 implementation, where the cached object gets mutated. ehcache3 package contains code with an EhCache3 implementation where the cached object is protected from mutation with just simple additional code while building the cache.

With just the addition of single line code below:

CacheConfigurationBuilder.withValueSerializingCopier(); 

the value for given key in cache provides the copy of the cached object.

The documentation for Serializers and Copiers is really awesome. I suggest you look into it. 🙂

With this simple implementation, I'm able to address the issue. But I spent a lot of time looking for it. I believe this short article helps you guys to narrow down your search on prevention of mutation of the cached object.

Creating Spring Boot Application for WebLogic and Tomcat
Defend Your Application with Netflix Hystrix