compareExchange
compareExchange是checkAndSet的特化版本:
- CheckSortKey和SetSortKey相同。
- CheckType为CT_VALUE_BYTES_EQUAL。该方法语义就是:如果SortKey对应的value存在且等于期望的值,则将其设置为新值。详细说明参见单行原子操作。
该方法与C++库中常见的atomic_compare_exchange语义基本保持一致。
- public static class CompareExchangeResult {
- /**
- * return value for CompareExchange
- *
- * @param setSucceed true if set value succeed.
- * @param actualValue return the actual value if set value failed; null means the actual value is not exist.
- */
- boolean setSucceed;
- byte[] actualValue;
- }
- /**
- * Atomically compare and exchange value by key.
- * <p>
- * - if the original value for the key is equal to the expected value, then update it with the desired value,
- * set CompareExchangeResult.setSucceed to true, and set CompareExchangeResult.actualValue to null because
- * the actual value must be equal to the desired value.
- * - if the original value for the key is not exist or not equal to the expected value, then set
- * CompareExchangeResult.setSucceed to false, and set the actual value in CompareExchangeResult.actualValue.
- * <p>
- * This method is very like the C++ function in {https://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange}.
- *
- * @param tableName the table name.
- * @param hashKey the hash key to compare and exchange.
- * @param sortKey the sort key to compare and exchange.
- * @param expectedValue the value expected to be found for the key.
- * @param desiredValue the desired value to set if the original value for the key is equal to the expected value.
- * @param ttlSeconds time to live in seconds of the desired value, 0 means no ttl.
- * @return CompareExchangeResult
- * @throws PException throws exception if any error occurs.
- */
- public PegasusTableInterface.CompareExchangeResult compareExchange(String tableName, byte[] hashKey, byte[] sortKey,
- byte[] expectedValue, byte[] desiredValue,
- 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。