Instantly share code, notes, and snippets.

What would you like to do?
(import 'java.text.SimpleDateFormat)
(let [lock (Object.)
date-format (SimpleDateFormat. "HH:mm:ss")]
(defn log [& msgs]
(locking lock
(apply println (str (.format date-format (java.util.Date.))) "-" (.getName (Thread/currentThread)) "-" msgs))))
;; This is just for logging the connection number
(def connections-created (atom 0))
(defn create-new-hbase-connection []
;;some side effecting code that creates a new socket
(Thread/sleep 1000)
(let [new-connection-number (swap! connections-created inc)]
(log "Connection created!" new-connection-number)
(def global-hbase-connection (atom (delay (create-new-hbase-connection))))
(defn refresh-connection! [broken-connection]
(if (compare-and-set! global-hbase-connection
(delay (create-new-hbase-connection)))
(log "closing connection" @broken-connection)))
(defn run-with-hbase [f]
(let [connection @global-hbase-connection]
(f @connection)
(catch Exception _
(refresh-connection! connection)
(log "Retrying")
(run-with-hbase f)))))
(dotimes [_ 4]
(future (run-with-hbase
(let [errored (atom false)]
(fn [connection]
(if @errored
(log "Using" connection)
(log "Not happy with" connection)
(reset! errored true)
(throw (RuntimeException.)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment