Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make random-fodder-seq thread safe #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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