[英]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.我正在使用番石榴 LoadingCache 来存储Animal
类型的对象,其中键是动物名称。 So far so good.到现在为止还挺好。
Then I get the cached object from using the get()
method and retrieve the Animal object.然后我使用get()
方法获取缓存的对象并检索 Animal 对象。 After that, I add a line like so: animal.setColor("blue");
之后,我添加这样一行: 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).我知道在 java 中修改对象也会将其更改为原始状态(类似于传递引用)。 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.没有可靠、有效、通用的方法来做到这一点——不过,在你的 Animal 类中编写一个复制构造函数是一种合乎逻辑的方法。
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.我也遇到过类似的情况,所以我使用了 apache commons 库中的SerializationUtils.clone
。 Make sure that this is not called very frequently because its deep copy mechanism is very slow as per javadoc.确保这不会被频繁调用,因为根据 javadoc,它的深层复制机制非常慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.