Skip to content

Commit 39d911b

Browse files
author
Cliff Rodgers + spinningtopsofdoom
committed
Make random-fodder-seq thread safe
- The details of the bug and fix are in the docstring of `hyperion.key/random-fodder-seq`.
1 parent b1b8f60 commit 39d911b

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

api/spec/hyperion/key_spec.clj

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@
4747
(should= true (seq? (random-fodder-seq)))
4848
(should= 10 (count (set (map (fn [_] (take 5 (random-fodder-seq))) (range 10))))))
4949

50+
(it "random-fodder-seq is threadsafe"
51+
(should= 250
52+
(reduce +
53+
(map
54+
(fn[_] (count (set (pmap
55+
(fn [_] (take 10 (random-fodder-seq)))
56+
(range 50)))))
57+
(range 5)))))
58+
5059
; (it "generate key times"
5160
; (prn (take 100 (iterate (fn [_] (generate-id)) nil)))
5261
; (prn (take 100 (iterate (fn [_] (generate-id2)) nil)))

api/src/hyperion/key.clj

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@
2323
(def fodder-count (count key-fodder))
2424

2525
(defn random-fodder-seq
26-
([] (random-fodder-seq (java.util.Random. (System/nanoTime))))
26+
"The default generator for `random-fodder-seq` is threadsafe for JDK 1.6b73
27+
or greater (http://bugs.java.com/view_bug.do?bug_id=6379897). Calls to this on
28+
multiple threads (i.e. `(pmap (fn [_] (take 10 random-fodder-seq)) (range 10))`)
29+
will have a different seed for each instance of `java.util.Random`. If on a JDK
30+
earlier than JDK 1.6b73 there is a chance that there will be multiple instances
31+
of `java.util.Random` with the same seed causing collisions"
32+
([] (random-fodder-seq (java.util.Random.)))
2733
([generator]
2834
(cons
2935
(aget key-fodder (.nextInt generator fodder-count))

0 commit comments

Comments
 (0)