compareExchange

compareExchange是checkAndSet的特化版本:

  • CheckSortKey和SetSortKey相同。
  • CheckType为CT_VALUE_BYTES_EQUAL。该方法语义就是:如果SortKey对应的value存在且等于期望的值,则将其设置为新值。详细说明参见单行原子操作

该方法与C++库中常见的atomic_compare_exchange语义基本保持一致。

  1. public static class CompareExchangeResult {
  2. /**
  3. * return value for CompareExchange
  4. *
  5. * @param setSucceed true if set value succeed.
  6. * @param actualValue return the actual value if set value failed; null means the actual value is not exist.
  7. */
  8. boolean setSucceed;
  9. byte[] actualValue;
  10. }
  11.  
  12. /**
  13. * Atomically compare and exchange value by key.
  14. * <p>
  15. * - if the original value for the key is equal to the expected value, then update it with the desired value,
  16. * set CompareExchangeResult.setSucceed to true, and set CompareExchangeResult.actualValue to null because
  17. * the actual value must be equal to the desired value.
  18. * - if the original value for the key is not exist or not equal to the expected value, then set
  19. * CompareExchangeResult.setSucceed to false, and set the actual value in CompareExchangeResult.actualValue.
  20. * <p>
  21. * This method is very like the C++ function in {https://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange}.
  22. *
  23. * @param tableName the table name.
  24. * @param hashKey the hash key to compare and exchange.
  25. * @param sortKey the sort key to compare and exchange.
  26. * @param expectedValue the value expected to be found for the key.
  27. * @param desiredValue the desired value to set if the original value for the key is equal to the expected value.
  28. * @param ttlSeconds time to live in seconds of the desired value, 0 means no ttl.
  29. * @return CompareExchangeResult
  30. * @throws PException throws exception if any error occurs.
  31. */
  32. public PegasusTableInterface.CompareExchangeResult compareExchange(String tableName, byte[] hashKey, byte[] sortKey,
  33. byte[] expectedValue, byte[] desiredValue,
  34. int ttlSeconds) throws PException;

注:

  • 参数:需传入TableName、HashKey、SortKey、ExpectedValue、DesiredValue、ttlSeconds。
    • hashKey、sortKey:用于指定数据的key。
    • expectedValue:期望的旧值。
    • desiredValue:如果旧值等于expectedValue,需要设置的新值。
    • ttlSeconds:新值的TTL时间;0表示不设置TTL限制。
  • 返回值:CompareExchangeResult,包括:
    • setSucceed:是否set成功,如果旧数据不存在,则set失败。
    • actualValue:如果set失败,返回该value的实际值;null表示不存在。
  • 异常:如果出现异常,譬如网络错误、超时错误、服务端错误等,会抛出 PException。