gets in Memcached, when used with Java, is commonly utilized to read data from the cache. Unlike a simple
gets also returns a unique identifier called 'CAS value' (Compare And Swap). This is particularly beneficial when multiple threads are potentially updating the same key and you want to avoid the "lost update" problem using optimistic locking.
Here we're using
spyMemcached, a well known Java client for Memcached.
Example 1 – Basic usage of
Example 2 - Utilizing the CAS token for a Compare And Swap operation
In the second example, a Memcached
cas operation is performed after retrieving the CAS token using
gets. If the
cas operation is successful, it means no other thread updated the key in between your gets and cas operations.
getsand the corresponding
casoperation when dealing with multi-threaded scenarios where the same key could be updated by different threads to avoid lost updates.
getsif you do not need CAS functionality. A simple
getoperation is less resource intensive.
getsas simply another
getsretrieves not just the value but also a CAS token which can be used for compare-and-swap operations.
gets, it's often because you intend to use the CAS token. If you don't need this, use
Q: What do I do if the
cas operation fails?
cas can fail if the item was updated by another client between your calls to
cas. In this situation, it's common to retry the whole read-modify-write cycle.