Skip to content

Instantly share code, notes, and snippets.

@bbbates
Created January 3, 2014 03:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbbates/8232007 to your computer and use it in GitHub Desktop.
Save bbbates/8232007 to your computer and use it in GitHub Desktop.
Using LockService to guarantee leader with Clojure and JGroups
(ns leader-guarantee.core
(:import (org.jgroups.blocks.locking LockService)
(org.jgroups.protocols CENTRAL_LOCK)
(org.jgroups JChannel)
(java.util.concurrent.locks Lock)))
(defn- get-lock
[lock-service with-lock-fn]
(fn []
(let [lock (.getLock lock-service "leader")]
(do
(.lock lock) ;; <<< Lock is acquired here - will block until Leader
(with-lock-fn)))))
(defn when-leader*
"Executes with-lock-fn when the local application container becomes leader of the cluster-name cluster."
[cluster-name with-lock-fn]
(let [channel (doto (JChannel.) ;; Uses udp by default
(.. getProtocolStack (addProtocol (doto (CENTRAL_LOCK.) (.init))))
(.connect cluster-name))
lock-service (LockService. channel)]
;; Create a thread to get us the Leader Lock
(doto (Thread. (get-lock lock-service with-lock-fn) "LeaderAppointmentThread")
(.setDaemon true)
(.start))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment