Skip to content

Instantly share code, notes, and snippets.

@mfikes

mfikes/thread-safe.clj

Last active Mar 7, 2018
Embed
What would you like to do?
(defn connection
"Promise to return a connection when one is available. If a
connection is not available, store the promise in server/state."
[]
(let [p (promise)
{:keys [deliver-conn]} (swap! state (fn [{:keys [connection] :as the-state}]
(if (and connection (not (.isClosed connection)))
(assoc the-state :connection nil
:deliver-conn connection)
(do
(when (:promised-conn the-state)
(println "OVERWRITE :promised-con"))
(assoc the-state :promised-conn p
:deliver-conn nil)))))]
(when deliver-conn
(deliver p deliver-conn))
p))
(defn set-connection
"Given a new available connection, either use it to deliver the
connection which was promised or store the connection for later
use."
[conn]
(let [{:keys [deliver-prom]} (swap! state (fn [{:keys [promised-conn] :as the-state}]
(if promised-conn
(assoc the-state :promised-conn nil
:deliver-prom promised-conn)
(do
(when (:connection the-state)
(println "OVERWRITE :connection"))
(assoc the-state :connection conn
:deliver-prom nil)))))]
(when deliver-prom
(deliver deliver-prom conn))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment