2 * Copyright 2015 Open Networking Laboratory
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onosproject.store.consistent.impl;
18 import org.onosproject.store.service.AsyncAtomicCounter;
19 import org.onosproject.store.service.AtomicCounter;
20 import org.onosproject.store.service.StorageException;
22 import java.util.concurrent.CompletableFuture;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
28 * Default implementation for a distributed AtomicCounter backed by
29 * partitioned Raft DB.
31 * The initial value will be zero.
33 public class DefaultAtomicCounter implements AtomicCounter {
35 private static final int OPERATION_TIMEOUT_MILLIS = 5000;
37 private final AsyncAtomicCounter asyncCounter;
39 public DefaultAtomicCounter(String name,
41 boolean meteringEnabled) {
42 asyncCounter = new DefaultAsyncAtomicCounter(name, database, meteringEnabled);
46 public long incrementAndGet() {
47 return complete(asyncCounter.incrementAndGet());
51 public long getAndIncrement() {
52 return complete(asyncCounter.getAndIncrement());
56 public long getAndAdd(long delta) {
57 return complete(asyncCounter.getAndAdd(delta));
61 public long addAndGet(long delta) {
62 return complete(asyncCounter.getAndAdd(delta));
67 return complete(asyncCounter.get());
70 private static <T> T complete(CompletableFuture<T> future) {
72 return future.get(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
73 } catch (InterruptedException e) {
74 Thread.currentThread().interrupt();
75 throw new StorageException.Interrupted();
76 } catch (TimeoutException e) {
77 throw new StorageException.Timeout();
78 } catch (ExecutionException e) {
79 throw new StorageException(e.getCause());