blob: e35990c7f95c8de0addca75aaf5c1744ef344d87 (
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
81
82
83
84
85
86
87
88
89
90
91
92
93
|
// 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.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
/**
* A distributed atomic counter.
*
* @author lulf
* @since 5.1
*/
public class CuratorCounter {
private final DistributedAtomicLong counter;
private final String counterPath;
public CuratorCounter(Curator curator, String counterPath) {
this.counter = curator.createAtomicCounter(counterPath);
this.counterPath = counterPath;
}
/**
* Atomically increment and return resulting value.
*
* @return the resulting value
* @throws IllegalStateException if increment fails
*/
public synchronized long next() {
try {
AtomicValue<Long> value = counter.increment();
if (!value.succeeded()) {
throw new IllegalStateException("Increment did not succeed");
}
return value.postValue();
} catch (Exception e) {
throw new IllegalStateException("Unable to get next value", e);
}
}
/**
* Atomically decrement and return the resulting value.
*
* @return the resulting value
* @throws IllegalStateException if decrement fails
*/
public synchronized long previous() {
try {
AtomicValue<Long> value = counter.subtract(1L);
if (!value.succeeded()) {
throw new IllegalStateException("Decrement did not succeed");
}
return value.postValue();
} catch (Exception e) {
throw new IllegalStateException("Unable to get previous value", e);
}
}
public synchronized void set(long current) {
try {
counter.trySet(current);
} catch (Exception e) {
throw new IllegalStateException("Unable to set value", e);
}
}
public long get() {
try {
AtomicValue<Long> value = counter.get();
if (!value.succeeded()) {
throw new RuntimeException("Get did not succeed");
}
return value.postValue();
} catch (Exception e) {
throw new RuntimeException("Unable to get value", e);
}
}
public void initialize(long value) {
try {
counter.initialize(value);
} catch (Exception e) {
throw new IllegalStateException("Error initializing atomic counter", e);
}
}
@Override
public String toString() {
return "curator counter " + counterPath;
}
}
|