blob: 038d995b88de8be6e245883ce84c5ca852d040b1 [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 */
Thomas Vachuskab6d31672018-07-27 17:03:46 -070016package org.onosproject.store.atomix.primitives.impl;
Jordan Halterman00e92da2018-05-22 23:05:52 -070017
18import java.time.Duration;
19import java.util.Optional;
20import java.util.concurrent.CompletableFuture;
21
22import org.onosproject.store.service.AsyncDistributedLock;
23import org.onosproject.store.service.Version;
24
Jordan Halterman6cf60c32018-08-15 01:22:51 -070025import static org.onosproject.store.atomix.primitives.impl.AtomixFutures.adaptFuture;
26
Jordan Halterman00e92da2018-05-22 23:05:52 -070027/**
28 * Atomix distributed lock.
29 */
30public class AtomixDistributedLock implements AsyncDistributedLock {
31 private final io.atomix.core.lock.AsyncAtomicLock atomixLock;
32
33 public AtomixDistributedLock(io.atomix.core.lock.AsyncAtomicLock atomixLock) {
34 this.atomixLock = atomixLock;
35 }
36
37 @Override
38 public String name() {
39 return atomixLock.name();
40 }
41
42 @Override
43 public CompletableFuture<Version> lock() {
Jordan Halterman6cf60c32018-08-15 01:22:51 -070044 return adaptFuture(atomixLock.lock()).thenApply(this::toVersion);
Jordan Halterman00e92da2018-05-22 23:05:52 -070045 }
46
47 @Override
48 public CompletableFuture<Optional<Version>> tryLock() {
Jordan Halterman6cf60c32018-08-15 01:22:51 -070049 return adaptFuture(atomixLock.tryLock()).thenApply(optional -> optional.map(this::toVersion));
Jordan Halterman00e92da2018-05-22 23:05:52 -070050 }
51
52 @Override
53 public CompletableFuture<Optional<Version>> tryLock(Duration timeout) {
Jordan Halterman6cf60c32018-08-15 01:22:51 -070054 return adaptFuture(atomixLock.tryLock(timeout)).thenApply(optional -> optional.map(this::toVersion));
Jordan Halterman00e92da2018-05-22 23:05:52 -070055 }
56
57 @Override
58 public CompletableFuture<Void> unlock() {
Jordan Halterman6cf60c32018-08-15 01:22:51 -070059 return adaptFuture(atomixLock.unlock());
Jordan Halterman00e92da2018-05-22 23:05:52 -070060 }
61
62 private Version toVersion(io.atomix.utils.time.Version version) {
63 return new Version(version.value());
64 }
65}