0

I have a Cached method that return object of some class. My app is multithreading. When one thread get cached object and process it, another thread also can get and modify this object and first thread has a problem.

@Cacheable(value="MyCache")
Script parse(String scriptText) {
    return new MyObject(scriptText);
}

How to configure it that method return a copy of cached object instead of the same object. Or how to serialize method result and deserialize when request a cached value.

I am using Spring Boot with Ehcache.

Max Valeev
  • 75
  • 5

2 Answers2

0

If you remove the cacheable annotation you will always get a new object. Is there a pressing reason to cache the object in the first place? Usually constructors are cheap. Is it possible the cache was a premature optimization?

Deadron
  • 5,135
  • 1
  • 16
  • 27
  • In my case constuct is expensive. There are executes some calculation based on 'scriptText' that not need to calculate again if get the same 'scriptText' – Max Valeev Aug 13 '20 at 03:11
0

Do not mutate objects that are returned from the cache.

Instead you should clone the object, mutate the clone and then update the cache with the new clone.

You can annotate methods that update objects in the cache with @CachePut.