Created
January 3, 2014 03:15
-
-
Save bbbates/8232007 to your computer and use it in GitHub Desktop.
Using LockService to guarantee leader with Clojure and JGroups
This file contains 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
(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