Product Documentation : Ehcache Configuration Guide : Configuring Cache : Passing Copies Instead of References
Passing Copies Instead of References
By default, a get() operation on a store returns a reference to the requested data, and any changes to that data are immediately reflected in the memory store. In cases where an application requires a copy of data rather than a reference to it, you can configure the store to return a copy. This allows you to change a copy of the data without affecting the original data in the memory store.
This is configured using the copyOnRead and copyOnWrite attributes of the <cache> and <defaultCache> elements in your configuration, or programmatically as follows:
CacheConfiguration config = new CacheConfiguration("copyCache", 1000)
.copyOnRead(true).copyOnWrite(true);
Cache copyCache = new Cache(config);
The default configuration is "false" for both options.
To copy elements on put()-like and/or get()-like operations, a copy strategy is used. The default implementation uses serialization to copy elements. You can provide your own implementation of net.sf.ehcache.store.compound.CopyStrategy using the <copyStrategy> element:
<cache name="copyCache"
maxEntriesLocalHeap="10"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="10"
copyOnRead="true"
copyOnWrite="true">
<copyStrategy class="com.company.ehcache.MyCopyStrategy"/>
</cache>
A single instance of your CopyStrategy is used per cache. Therefore, in your implementation of CopyStrategy.copy(T), T must be thread-safe.
A copy strategy can be added programmatically in the following way:
CacheConfiguration cacheConfiguration = new CacheConfiguration("copyCache", 10);
CopyStrategyConfiguration copyStrategyConfiguration = new CopyStrategyConfiguration();
copyStrategyConfiguration.setClass("com.company.ehcache.MyCopyStrategy");
cacheConfiguration.addCopyStrategy(copyStrategyConfiguration);
Copyright © 2010-2015 Software AG, Darmstadt, Germany.

Product Logo |   Feedback