blob: e479028ec10b6be67f4074d106096b3b923c4e0c [file] [log] [blame]
Madan Jampanib5d72d52015-04-03 16:53:50 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.consistent.impl;
17
18import java.util.concurrent.CompletableFuture;
19import java.util.concurrent.ExecutionException;
20import java.util.concurrent.TimeUnit;
21import java.util.concurrent.TimeoutException;
22
23import org.onosproject.store.service.AsyncAtomicCounter;
24import org.onosproject.store.service.AtomicCounter;
25import org.onosproject.store.service.StorageException;
26
27/**
28 * Default implementation for a distributed AtomicCounter backed by
29 * partitioned Raft DB.
30 * <p>
31 * The initial value will be zero.
32 */
33public class DefaultAtomicCounter implements AtomicCounter {
34
35 private static final int OPERATION_TIMEOUT_MILLIS = 5000;
36
37 private final AsyncAtomicCounter asyncCounter;
38
39 public DefaultAtomicCounter(String name, Database database) {
40 asyncCounter = new DefaultAsyncAtomicCounter(name, database);
41 }
42
43 @Override
44 public long incrementAndGet() {
45 return complete(asyncCounter.incrementAndGet());
46 }
47
48 @Override
49 public long get() {
50 return complete(asyncCounter.get());
51 }
52
53 private static <T> T complete(CompletableFuture<T> future) {
54 try {
55 return future.get(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
56 } catch (InterruptedException e) {
57 Thread.currentThread().interrupt();
58 throw new StorageException.Interrupted();
59 } catch (TimeoutException e) {
60 throw new StorageException.Timeout();
61 } catch (ExecutionException e) {
62 throw new StorageException(e.getCause());
63 }
64 }
65}