简体   繁体   中英

How can I get the value of a cache from guava cacheloader and update the value without changing the value in cache?

I'm using a guava LoadingCache to store objects of type Animal where the key is an animal name. So far so good.

Then I get the cached object from using the get() method and retrieve the Animal object. After that, I add a line like so: animal.setColor("blue");

After that I realized the previous color in the guava cache is also being changed. I know that modifying an object in java changes it for the original state as well (similar to pass-by-reference). But for caching I think this will introduce some weird bugs in my code. How can I get the copy and not worry about if some code is updating the object that was just retrieved from the cache?

You must copy the object after getting it from the cache. There's no reliable, efficient, general way to do that -- writing a copy constructor in your Animal class is a logical approach, though.

Or you could stop using mutable objects, which prevents these sorts of bugs universally.

I also faced similar situation so I used SerializationUtils.clone from apache commons library. Make sure that this is not called very frequently because its deep copy mechanism is very slow as per javadoc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM