【发布时间】:2020-05-19 22:08:14
【问题描述】:
在处理数据需要在 UUID 上排序的用例时,这些 UUID 都是 Type 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))));
}
我使用 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
从上面可以看出 uuid1 小于 uuid2,但是当我们使用 UUID compareTo 方法比较它们时,我们得到不同的输出。我们应该得到 -1 的输出,因为它应该小于但我们得到的答案是 1,这表明这个 uuid1 大于 uuid2
uuid1.compareTo(uuid2) //output - 1
进一步分析,发现 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
这种行为对于 UUID 及其相互比较是否正常? 如果是这样,那么我们如何处理此类基于时间的 UUID 的排序?
谢谢
【问题讨论】:
-
当一个大数变为负数时,这通常意味着发生了溢出。不知道这里会发生什么。
标签: java sorting cassandra datastax-java-driver timeuuid