Import atomix/{storage,utils}
[controller.git] / third-party / atomix / utils / src / main / java / io / atomix / utils / time / LogicalClock.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 static com.google.common.base.MoreObjects.toStringHelper;
19
20 /**
21  * Logical clock.
22  */
23 public class LogicalClock implements Clock<LogicalTimestamp> {
24   private LogicalTimestamp currentTimestamp;
25
26   public LogicalClock() {
27     this(new LogicalTimestamp(0));
28   }
29
30   public LogicalClock(LogicalTimestamp currentTimestamp) {
31     this.currentTimestamp = currentTimestamp;
32   }
33
34   @Override
35   public LogicalTimestamp getTime() {
36     return currentTimestamp;
37   }
38
39   /**
40    * Increments the clock and returns the new timestamp.
41    *
42    * @return the updated clock time
43    */
44   public LogicalTimestamp increment() {
45     return update(new LogicalTimestamp(currentTimestamp.value() + 1));
46   }
47
48   /**
49    * Updates the clock using the given timestamp.
50    *
51    * @param timestamp the timestamp with which to update the clock
52    * @return the updated clock time
53    */
54   public LogicalTimestamp update(LogicalTimestamp timestamp) {
55     if (timestamp.value() > currentTimestamp.value()) {
56       this.currentTimestamp = timestamp;
57     }
58     return currentTimestamp;
59   }
60
61   /**
62    * Increments the clock and updates it using the given timestamp.
63    *
64    * @param timestamp the timestamp with which to update the clock
65    * @return the updated clock time
66    */
67   public LogicalTimestamp incrementAndUpdate(LogicalTimestamp timestamp) {
68     long nextValue = currentTimestamp.value() + 1;
69     if (timestamp.value() > nextValue) {
70       return update(timestamp);
71     }
72     return increment();
73   }
74
75   @Override
76   public String toString() {
77     return toStringHelper(this)
78         .add("time", getTime())
79         .toString();
80   }
81 }