1
2

More than 3 years have passed since last update.

ULID生成順を保持する

Posted at

TL;DR;

https://github.com/ulid/spec#monotonicity
を参照
Kotlin or Javaの方法を求めてきた方はulid.nextValue().increment()を使用

前提

https://github.com/ulid/spec
Kotlin 1.3.50
huxi ulidを使用
kotlin Scratchにて実験

失敗例

import de.huxhorn.sulky.ulid.ULID

val ulid = ULID()
val pairs = (0..1000).map {
  val now = System.currentTimeMillis()
  Pair(now, Pair(it, ulid.nextULID(now)))
}
val sorted = pairs.sortedBy { it.second.second }
println("\n\n\n" + sorted.take(10).joinToString("\n") { Pair(it.first, it.second.first).toString() })
//scratch.kts:9 (1571214567664, 0)
//scratch.kts:9 (1571214567665, 5)
//scratch.kts:9 (1571214567665, 1)
//scratch.kts:9 (1571214567665, 2)
//scratch.kts:9 (1571214567665, 4)
//scratch.kts:9 (1571214567665, 7)
//scratch.kts:9 (1571214567665, 6)
//scratch.kts:9 (1571214567665, 3)
//scratch.kts:9 (1571214567666, 15)
//scratch.kts:9 (1571214567666, 10)

同じミリ秒内に生成された物の順番は保証されない。

成功例

import de.huxhorn.sulky.ulid.ULID

val ulid = ULID()
var value = ulid.nextValue()
val pairs = (0..1000).map {
  val now = System.currentTimeMillis()
  Pair(now, Pair(it, value.increment().toString()))
}
val sorted = pairs.sortedBy { it.second.second }
println("\n\n\n" + sorted.take(10).joinToString("\n") { Pair(it.first, it.second.first).toString() })
//scratch.kts:10 (1571215418684, 0)
//scratch.kts:10 (1571215418685, 1)
//scratch.kts:10 (1571215418685, 2)
//scratch.kts:10 (1571215418685, 3)
//scratch.kts:10 (1571215418685, 4)
//scratch.kts:10 (1571215418685, 5)
//scratch.kts:10 (1571215418685, 6)
//scratch.kts:10 (1571215418685, 7)
//scratch.kts:10 (1571215418685, 8)
//scratch.kts:10 (1571215418685, 9)
var value = ulid.nextValue()
  Pair(now, Pair(it, value.increment().toString()))

前の値を保持しておいてincrementしているだけだがgithubには載っていなかったのでまとめた。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2