In RawKV, compare-and-swap (CAS) is an atomic operation used to avoid data racing in concurrent write requests, which is atomically equivalent to:

    Normally, CAS can prevent problems from the concurrent access, but suffers from the .

    1. import java.util.Optional;
    2. import org.tikv.common.TiConfiguration;
    3. import org.tikv.common.TiSession;
    4. import org.tikv.raw.RawKVClient;
    5. import org.tikv.shade.com.google.protobuf.ByteString;
    6. TiConfiguration conf = TiConfiguration.createRawDefault("127.0.0.1:2379");
    7. // enable AtomicForCAS when using RawKVClient.compareAndSet or RawKVClient.putIfAbsent
    8. conf.setEnableAtomicForCAS(true);
    9. TiSession session = TiSession.create(conf);
    10. RawKVClient client = session.createRawClient();
    11. ByteString key = ByteString.copyFromUtf8("Hello");
    12. ByteString newValue = ByteString.copyFromUtf8("NewValue");
    13. // put
    14. client.put(key, value);
    15. // get
    16. Optional<ByteString> result = client.get(key);
    17. assert(result.isPresent());
    18. assert("CAS".equals(result.get().toStringUtf8()));
    19. // cas
    20. client.compareAndSet(key, Optional.of(value), newValue);
    21. result = client.get(key);
    22. assert(result.isPresent());
    23. assert("NewValue".equals(result.get().toStringUtf8()));
    24. System.out.println(result.get().toStringUtf8());
    25. // close
    26. session.close();

    You must set conf.setEnableAtomicForCAS(true) to ensure linearizability of CAS when using with put, delete, batch_put, or batch_delete.

    The code example used in this chapter can be found .