Skip to content

Commit

Permalink
Make random-fodder-seq thread safe
Browse files Browse the repository at this point in the history
- The details of the bug and fix are in the docstring of
`hyperion.key/random-fodder-seq`.
  • Loading branch information
Cliff Rodgers + spinningtopsofdoom committed Oct 8, 2015
1 parent b1b8f60 commit 39d911b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
9 changes: 9 additions & 0 deletions api/spec/hyperion/key_spec.clj
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@
(should= true (seq? (random-fodder-seq)))
(should= 10 (count (set (map (fn [_] (take 5 (random-fodder-seq))) (range 10))))))

(it "random-fodder-seq is threadsafe"
(should= 250
(reduce +
(map
(fn[_] (count (set (pmap
(fn [_] (take 10 (random-fodder-seq)))
(range 50)))))
(range 5)))))

; (it "generate key times"
; (prn (take 100 (iterate (fn [_] (generate-id)) nil)))
; (prn (take 100 (iterate (fn [_] (generate-id2)) nil)))
Expand Down
8 changes: 7 additions & 1 deletion api/src/hyperion/key.clj
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@
(def fodder-count (count key-fodder))

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

0 comments on commit 39d911b

Please sign in to comment.