Skip to content

Instantly share code, notes, and snippets.

@favila
Created June 1, 2015 23:26
Show Gist options
  • Save favila/5e321cd54cc27c323ad4 to your computer and use it in GitHub Desktop.
Save favila/5e321cd54cc27c323ad4 to your computer and use it in GitHub Desktop.
AtomicInteger counter with overflow handled correctly
(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