Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ehcache Update Element

Am using the below code to do an update to an element in the cache.

Cache cache = manager.getCache("myCache");
cache.put(new Element("k1", "v1"));
//updates "k1"
cache.put(new Element("k1", "v2"));

Is this thread safe or do we need to do anything beyond this for thread safety. Also from a performance perspective, every update results in a new Element. Is this a good approach?

Regards

like image 364
oxygenan Avatar asked Feb 23 '26 09:02

oxygenan


1 Answers

This is the basic API to update cache entries: do a put for the same key with an updated value. In order to do this, you indeed need to create a new Element.

Regarding the thread safety, Ehcache operations are thread safe by design.

But I am not sure what is your context and requirement for thread safety.

Nothing prevents another thread to update the same key at any time of your processing, including between the two puts. If you want to guarantee that the second put only updates key k1 if its value is still v1, then you need to have a look at the provided Compare and Swap Operations or at explicit locking.

like image 154
Louis Jacomet Avatar answered Feb 24 '26 23:02

Louis Jacomet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!