problem when Spring Boot integrates Caffeine Cache: cache object obtained is different from the object set originally

created at 12-14-2021 views: 31

problem

When using the local cache Caffeine, I encountered a problem. The code logic is roughly as follows. First, try to obtain the Apple object from the local cache according to the Key. If it is not obtained, then initialize a named "Little Peanut" Apple and put it in the local cache of Caffeine.

But after putting it out, I made another setting for this object, changing the name from "Little Peanut" to Lingye Jun, but so far I returned the object directly, and did not put the object in the cache a second time. Go in.

Then, think about it, at this time, the name of the Apple object in the cache is Little Peanuts? The problem that arises today is that the `name` of the Apple object in the cache is no longer Little Peanut, but becomes Lingyejun.

private Apple getAppleByCaffeineCache() {

     String cacheKey = "lingyejun.cache.apple";

     Apple apple = (Apple) cache.getIfPresent(cacheKey);

     if (Objects.isNull(apple)) {
         apple = new Apple();
         apple.setName("Little Peanuts");
         cache.put(cacheKey, apple);
     }

     apple.setName("Ling Ye Jun");

     return apple;
}

reason

Searching on the Internet, the so-called memory cache, we can understand that the data we cache all exist in a class managed by the cache framework, and the data we cache is used as an attribute of this class.

When we try to get the value we need from the cache, we call a get method of this class. This class holds a reference to the data we store, and a reference to the data we need from the cache. When we modify data by reference, we modify the actual data itself pointed to by the reference.

Therefore, after we modify the data obtained from the cache, the data actually stored in the cache is also modified, and then we fetch it from the cache to obtain the modified data.

solution

If we need to do the next logical processing for this object after we take out the cached object in the method, then we can copy this object into a new object, and the operation for this new object will not affect our cache. The object of it.

created at:12-14-2021
edited at: 12-14-2021: