Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / time / Version.java
1 /*
2  * Copyright 2017-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  */
16 package io.atomix.utils.time;
17
18 import com.google.common.collect.ComparisonChain;
19
20 import java.util.Objects;
21
22 import static com.google.common.base.MoreObjects.toStringHelper;
23 import static com.google.common.base.Preconditions.checkArgument;
24
25 /**
26  * Logical timestamp for versions.
27  * <p>
28  * The version is a logical timestamp that represents a point in logical time at which an event occurs.
29  * This is used in both pessimistic and optimistic locking protocols to ensure that the state of a shared resource
30  * has not changed at the end of a transaction.
31  */
32 public class Version implements Timestamp {
33   private final long version;
34
35   public Version(long version) {
36     this.version = version;
37   }
38
39   /**
40    * Returns the version.
41    *
42    * @return the version
43    */
44   public long value() {
45     return this.version;
46   }
47
48   @Override
49   public int compareTo(Timestamp o) {
50     checkArgument(o instanceof Version,
51         "Must be LockVersion", o);
52     Version that = (Version) o;
53
54     return ComparisonChain.start()
55         .compare(this.version, that.version)
56         .result();
57   }
58
59   @Override
60   public int hashCode() {
61     return Long.hashCode(version);
62   }
63
64   @Override
65   public boolean equals(Object obj) {
66     if (this == obj) {
67       return true;
68     }
69     if (!(obj instanceof Version)) {
70       return false;
71     }
72     Version that = (Version) obj;
73     return Objects.equals(this.version, that.version);
74   }
75
76   @Override
77   public String toString() {
78     return toStringHelper(getClass())
79         .add("version", version)
80         .toString();
81   }
82 }