Skip to content

Commit

Permalink
Fix ThreadLocalRandom
Browse files Browse the repository at this point in the history
Current impl was not creating thread local randoms!
  • Loading branch information
isaacl committed Sep 12, 2024
1 parent a104e9b commit b6031ad
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lila/src/main/scala/Random.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ package scalalib

import scala.collection.mutable.StringBuilder

val ThreadLocalRandom = RandomApi(java.util.concurrent.ThreadLocalRandom.current)
import scala.collection.mutable.StringBuilder

private final val store =
java.lang.ThreadLocal.withInitial(() => RandomApi(java.util.concurrent.ThreadLocalRandom.current))

def ThreadLocalRandom = store.get

val SecureRandom = RandomApi(java.security.SecureRandom())

Expand Down
12 changes: 12 additions & 0 deletions lila/src/test/scala/RandomTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package scalalib

class RandomTest extends munit.FunSuite:

test("different threads get different randoms"):
val r1 = ThreadLocalRandom

@volatile var r2: RandomApi = null
val thread2 = new Thread(() => r2 = ThreadLocalRandom)
thread2.start()
thread2.join()
assertNotEquals(r1, r2)

0 comments on commit b6031ad

Please sign in to comment.