blob: dc75940aca9c42b9f3310de4a402e546852a435a [file] [log] [blame]
Yuta HIGUCHI598e57e2014-06-16 21:19:01 -07001package net.onrc.onos.core.datastore.ramcloud;
2
3import org.slf4j.Logger;
4import org.slf4j.LoggerFactory;
5
6import net.onrc.onos.core.datastore.IKVTable;
7import net.onrc.onos.core.datastore.IKVTableID;
8import net.onrc.onos.core.datastore.ObjectDoesntExistException;
9import net.onrc.onos.core.datastore.ObjectExistsException;
10import net.onrc.onos.core.datastore.IKVTable.IKVEntry;
11import net.onrc.onos.core.datastore.utils.ByteArrayUtil;
12import net.onrc.onos.core.util.distributed.DistributedAtomicLong;
13
14/**
15 * RAMCloudImplementation of DistributedAtomicLong.
16 */
17public class RCDistributedAtomicLong implements DistributedAtomicLong {
18 private static final String PREFIX = "DAL:";
19 private static final byte[] KEY = {0};
20 private static final byte[] ZERO = ByteArrayUtil.toLEBytes(0L);
21
22 private static final Logger log = LoggerFactory.getLogger(RCDistributedAtomicLong.class);
23
24
25 private final RCClient client;
26 private final String name;
27 private final IKVTableID tableID;
28
29
30 /**
31 * Creates or Gets the DistributedAtomicLong instance.
32 *
33 * @param client client to use.
34 * @param name name of the DistributedAtomicLong instance.
35 */
36 public RCDistributedAtomicLong(final RCClient client, final String name) {
37
38 this.client = client;
39 this.name = name;
40 IKVTable table = client.getTable(PREFIX + name);
41 this.tableID = table.getTableId();
42
43 try {
44 table.create(KEY, ZERO);
45 } catch (ObjectExistsException e) {
46 log.trace("RCDistributedAtomicLong {} already exists", name);
47 }
48 }
49
50 @Override
51 public long get() {
52 try {
53 IKVEntry entry = client.read(tableID, KEY);
54 return ByteArrayUtil.fromLEBytes(entry.getValue());
55 } catch (ObjectDoesntExistException e) {
56 log.error("RCDistributedAtomicLong {} does not exist", name);
57 throw new IllegalStateException(name + " does not exist", e);
58 }
59 }
60
61 @Override
62 public long addAndGet(long delta) {
63 return client.incrementCounter(tableID, KEY, delta);
64 }
65
66 @Override
67 public void set(long newValue) {
68 client.setCounter(tableID, KEY, newValue);
69 }
70
71 @Override
72 public long incrementAndGet() {
73 return addAndGet(1L);
74 }
75
76}