1
votes

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?

2

2 Answers

2
votes

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.

0
votes

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.