mercredi 5 février 2020

Distribution difference between Kotlin Random and Java Random

Considering the following code:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import java.util.concurrent.ConcurrentSkipListSet
import java.util.Random

val ids = ConcurrentSkipListSet<String>()

fun append(id: String) {
    if (ids.contains(id)) throw RuntimeException("Repeated: $id")
    ids.add(id)
}

fun main() = runBlocking<Unit> {
    val rnd = Random(System.nanoTime())
    delay(1000)

    val scope = CoroutineScope(newFixedThreadPoolContext(32, "MyThread"))
    repeat(10_000_000) {
        scope.launch {
            val high = rnd.nextLong()
            val low = rnd.nextLong()

            append("$high:$low")
        }
    }

    scope.coroutineContext[Job]?.children?.forEach { it.join() }
}

Running on MacOS 10.14.6, Kotlin 1.3 and JVM 1.8, I could not produce any repeated id. However, after replacing import java.util.Random with import kotlin.random.Random, I am able to produce repeated id almost immediately (after 25000 generation). Is this something expected regarding to XorWow algorithm?




Aucun commentaire:

Enregistrer un commentaire