summaryrefslogtreecommitdiffstats
path: root/zkfacade
diff options
context:
space:
mode:
authorJon Bratseth <bratseth@yahoo-inc.com>2017-06-28 13:23:46 +0200
committerJon Bratseth <bratseth@yahoo-inc.com>2017-06-28 13:23:46 +0200
commitb32248cf458a04ffe3cfcf0242e2edc6e28461a8 (patch)
treea923bbcd947d64c9f414f56ff0b2f260f0060f0a /zkfacade
parent0229966296d14040a3dfdf7003271adc7fdf7fc0 (diff)
Move CuratorMutex to make it reusable
Diffstat (limited to 'zkfacade')
-rw-r--r--zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorMutex.java53
1 files changed, 53 insertions, 0 deletions
diff --git a/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorMutex.java b/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorMutex.java
new file mode 100644
index 00000000000..e3dee56fcd6
--- /dev/null
+++ b/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorMutex.java
@@ -0,0 +1,53 @@
+// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.curator;
+
+import com.google.common.util.concurrent.UncheckedTimeoutException;
+import com.yahoo.transaction.Mutex;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.recipes.locks.InterProcessMutex;
+
+import java.time.Duration;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A cluster-wide reentrant mutex which is released on (the last symmetric) close
+ *
+ * @author bratseth
+ */
+public class CuratorMutex implements Mutex {
+
+ private final InterProcessMutex mutex;
+ private final String lockPath;
+
+ public CuratorMutex(String lockPath, CuratorFramework curator) {
+ this.lockPath = lockPath;
+ mutex = new InterProcessMutex(curator, lockPath);
+ }
+
+ /** Take the lock with the given timeout. This may be called multiple times from the same thread - each matched by a close */
+ public void acquire(Duration timeout) {
+ boolean acquired;
+ try {
+ acquired = mutex.acquire(timeout.toMillis(), TimeUnit.MILLISECONDS);
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Exception acquiring lock '" + lockPath + "'", e);
+ }
+
+ if (! acquired) throw new UncheckedTimeoutException("Timed out after waiting " + timeout.toString() +
+ " to acquire lock + '" + lockPath + "'");
+ }
+
+ @Override
+ public void close() {
+ try {
+ mutex.release();
+ }
+ catch (Exception e) {
+ throw new RuntimeException("Exception releasing lock '" + lockPath + "'");
+ }
+ }
+
+}
+
+