Java UUID compareTo 对于 Type1 UUID 无法正常工作

bla*_*der 5 java sorting cassandra datastax-java-driver timeuuid

在处理数据需要在 UUID 上排序的用例时,这些数据都是类型 1 或基于时间并使用 Datastax Cassandra Java 驱动程序库 (UUIDS.timebased()) 生成的,我发现 UUID.compareTo 没有对某些数据进行排序UUID 正确。compareTo 中的逻辑是

    /**
 * Compares this UUID with the specified UUID.
 *
 * <p> The first of two UUIDs is greater than the second if the most
 * significant field in which the UUIDs differ is greater for the first
 * UUID.
 *
 * @param  val
 *         {@code UUID} to which this {@code UUID} is to be compared
 *
 * @return  -1, 0 or 1 as this {@code UUID} is less than, equal to, or
 *          greater than {@code val}
 *
 */
public int compareTo(UUID val) {
    // The ordering is intentionally set up so that the UUIDs
    // can simply be numerically compared as two numbers
    return (this.mostSigBits < val.mostSigBits ? -1 :
            (this.mostSigBits > val.mostSigBits ? 1 :
             (this.leastSigBits < val.leastSigBits ? -1 :
              (this.leastSigBits > val.leastSigBits ? 1 :
               0))));
}
Run Code Online (Sandbox Code Playgroud)

我使用 java 的 datastax cassandra 驱动程序生成了以下 2 个 UUID。

UUID uuid1 = java.util.UUID.fromString("7fff5ab0-43be-11ea-8fba-0f6f28968a17")
UUID uuid2 = java.util.UUID.fromString("80004510-43be-11ea-8fba-0f6f28968a17")
uuid1.timestamp() //137997224058510000
uuid2.timestamp() //137997224058570000
Run Code Online (Sandbox Code Playgroud)

从上面可以看出,uuid1 比 uuid2 小,但是当我们使用 UUID compareTo 方法比较它们时,我们得到了不同的输出。我们应该得到 -1 的输出,因为它应该小于但我们得到的答案是 1,这表明这个 uuid1 大于 uuid2

uuid1.compareTo(uuid2) //output - 1
Run Code Online (Sandbox Code Playgroud)

在进一步分析这一点时,发现 uuid2 的 msb 转换为负数,而 uuid1 的 msb 是正数。因此,compareTo 中的逻辑返回值 1 而不是 -1。

u_7fff5ab0 = {UUID@2623} "7fff5ab0-43be-11ea-8fba-0f6f28968a17"
mostSigBits = 9223190274975338986
leastSigBits = -8090136810520933865

u_80004510 = {UUID@2622} "80004510-43be-11ea-8fba-0f6f28968a17"
mostSigBits = -9223296100696452630
leastSigBits = -8090136810520933865
Run Code Online (Sandbox Code Playgroud)

这种行为对于 UUID 及其相互比较是否正常?如果是这样,那么我们如何处理这种基于时间的 UUID 的排序?

谢谢

ruh*_*hul 3

请注意,比较基于时间的 UUID 需要特别小心,来自文档

最后,请注意 Cassandra 的 timeuuid 排序与 UUID.compareTo(java.util.UUID) 不兼容,因此此方法创建的 UUID 不一定是后一种方法的下限。

基于时间的 UUID 不应与java.util.UUID#compareTo. 要比较两个基于时间的 UUID,您应该比较时间;这两个UUID内包含。您需要自定义实用程序方法实现或仅比较两个时间戳。以下是如何执行此操作的示例:

// must be timebased UUID
int compareTo(UUID a, UUID b){
   return Long.compare(UUIDs.unixTimestamp(a),UUIDs.unixTimestamp(b));
}
Run Code Online (Sandbox Code Playgroud)

要了解更多信息,请浏览此文档