2 * Copyright 2017-present Open Networking Foundation
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 io.atomix.utils.time;
18 import static com.google.common.base.MoreObjects.toStringHelper;
23 public class LogicalClock implements Clock<LogicalTimestamp> {
24 private LogicalTimestamp currentTimestamp;
26 public LogicalClock() {
27 this(new LogicalTimestamp(0));
30 public LogicalClock(LogicalTimestamp currentTimestamp) {
31 this.currentTimestamp = currentTimestamp;
35 public LogicalTimestamp getTime() {
36 return currentTimestamp;
40 * Increments the clock and returns the new timestamp.
42 * @return the updated clock time
44 public LogicalTimestamp increment() {
45 return update(new LogicalTimestamp(currentTimestamp.value() + 1));
49 * Updates the clock using the given timestamp.
51 * @param timestamp the timestamp with which to update the clock
52 * @return the updated clock time
54 public LogicalTimestamp update(LogicalTimestamp timestamp) {
55 if (timestamp.value() > currentTimestamp.value()) {
56 this.currentTimestamp = timestamp;
58 return currentTimestamp;
62 * Increments the clock and updates it using the given timestamp.
64 * @param timestamp the timestamp with which to update the clock
65 * @return the updated clock time
67 public LogicalTimestamp incrementAndUpdate(LogicalTimestamp timestamp) {
68 long nextValue = currentTimestamp.value() + 1;
69 if (timestamp.value() > nextValue) {
70 return update(timestamp);
76 public String toString() {
77 return toStringHelper(this)
78 .add("time", getTime())