Created
June 20, 2017 18:44
-
-
Save dlebrero/5b87a36a487d99b1963d5dceaa381085 to your computer and use it in GitHub Desktop.
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.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) | |
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 | |
broken-connection | |
(delay (create-new-hbase-connection))) | |
(log "closing connection" @broken-connection))) | |
(defn run-with-hbase [f] | |
(let [connection @global-hbase-connection] | |
(try | |
(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) | |
(do | |
(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