blob: 977b2069f6c1b7a130529f074274927bc3c97310 [file] [log] [blame]
Jordan Halterman00e92da2018-05-22 23:05:52 -07001/*
2 * Copyright 2018-present Open Networking Foundation
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.primitives.impl;
17
18import java.util.Map;
19import java.util.concurrent.CompletableFuture;
20
21import com.google.common.collect.Maps;
22import org.onosproject.store.service.AsyncAtomicValue;
23import org.onosproject.store.service.AtomicValueEvent;
24import org.onosproject.store.service.AtomicValueEventListener;
25
26/**
27 * Atomix atomic value.
28 */
29public class AtomixAtomicValue<V> implements AsyncAtomicValue<V> {
30 private final io.atomix.core.value.AsyncAtomicValue<V> atomixValue;
31 private final Map<AtomicValueEventListener<V>, io.atomix.core.value.AtomicValueEventListener<V>> listenerMap =
32 Maps.newIdentityHashMap();
33
34 public AtomixAtomicValue(io.atomix.core.value.AsyncAtomicValue<V> atomixValue) {
35 this.atomixValue = atomixValue;
36 }
37
38 @Override
39 public String name() {
40 return atomixValue.name();
41 }
42
43 @Override
44 public CompletableFuture<Boolean> compareAndSet(V expect, V update) {
45 return atomixValue.compareAndSet(expect, update);
46 }
47
48 @Override
49 public CompletableFuture<V> get() {
50 return atomixValue.get();
51 }
52
53 @Override
54 public CompletableFuture<V> getAndSet(V value) {
55 return atomixValue.getAndSet(value);
56 }
57
58 @Override
59 public CompletableFuture<Void> set(V value) {
60 return atomixValue.set(value);
61 }
62
63 @Override
64 public synchronized CompletableFuture<Void> addListener(AtomicValueEventListener<V> listener) {
65 io.atomix.core.value.AtomicValueEventListener<V> atomixListener = event ->
66 listener.event(new AtomicValueEvent<V>(
67 name(),
68 event.newValue(),
69 event.oldValue()));
70 listenerMap.put(listener, atomixListener);
71 return atomixValue.addListener(atomixListener);
72 }
73
74 @Override
75 public synchronized CompletableFuture<Void> removeListener(AtomicValueEventListener<V> listener) {
76 io.atomix.core.value.AtomicValueEventListener<V> atomixListener = listenerMap.remove(listener);
77 if (atomixListener != null) {
78 return atomixValue.removeListener(atomixListener);
79 }
80 return CompletableFuture.completedFuture(null);
81 }
82}