summaryrefslogtreecommitdiffstats
path: root/zkfacade/src/main/java/com/yahoo/vespa/curator/recipes/CuratorLock.java
blob: 6247cc1aa2cc2a66cbb650eff422a83703255b0e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// 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.recipes;

import com.yahoo.vespa.curator.Curator;
import org.apache.curator.framework.recipes.locks.InterProcessLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author lulf
 * @since 5.1
 */
public class CuratorLock implements Lock {

    private final InterProcessLock mutex;

    public CuratorLock(Curator curator, String lockPath) {
        this.mutex = curator.createMutex(lockPath);
    }

    public boolean hasLock() {
        return mutex.isAcquiredInThisProcess();
    }

    @Override
    public void lock() {
        try {
            mutex.acquire();
        } catch (Exception e) {
            throw new CuratorLockException(e);
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean tryLock() {
        try {
            return tryLock(0, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new CuratorLockException(e);
        }
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        try {
            return mutex.acquire(time, unit);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            throw new CuratorLockException(e);
        }
    }

    @Override
    public void unlock() {
        try {
            mutex.release();
        } catch (Exception e) {
            throw new CuratorLockException(e);
        }
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }


    @Override
    public String toString() {
        return mutex.toString();
    }
}