Created
June 1, 2015 23:26
-
-
Save favila/5e321cd54cc27c323ad4 to your computer and use it in GitHub Desktop.
AtomicInteger counter with overflow handled correctly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(import '[java.util.concurrent.atomic AtomicInteger]) | |
(set! *unchecked-math* :warn-on-boxed) | |
(def ^AtomicInteger counter (AtomicInteger.)) | |
(defn next-tempid-idx [^AtomicInteger i] | |
(unchecked-subtract -1000000 (bit-and (.getAndIncrement i) 0x7fffffff))) | |
(next-tempid-idx counter) | |
;=> -1000000 | |
(next-tempid-idx counter) | |
;=> -1000001 | |
(next-tempid-idx counter) | |
;=> -1000002 | |
(.set counter Integer/MAX_VALUE) | |
;=> nil | |
(next-tempid-idx counter) | |
;=> -2148483647 | |
(next-tempid-idx counter) | |
;=> -1000000 | |
(next-tempid-idx counter) | |
;=> -1000001 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment