混合時鐘

使用系統時間戳記和邏輯時間戳記的組合,將版本設為可排序的日期和時間

問題

Lamport 時鐘 用於 版本化值 中的版本時,客戶端不知道特定版本儲存的實際日期時間。客戶端使用日期和時間(例如 01-01-2020)存取版本會比使用整數(例如 1、2、3)更方便。

解決方案

混合邏輯時鐘 提供一種方法,可以擁有像簡單整數一樣單調遞增的版本,但同時與實際日期和時間相關。混合時鐘實際上由 MongoDB 或 CockroachDB 等資料庫使用。

它將最新時間維護為混合時間戳記的實例,該實例由系統時間和整數計數器建構而成。

類別 HybridTimestamp…

  public class HybridTimestamp implements Comparable<HybridTimestamp> {
      private final long wallClockTime;
      private final int ticks;
  
      public HybridTimestamp(long systemTime, int ticks) {
          this.wallClockTime = systemTime;
          this.ticks = ticks;
      }
  
      public static HybridTimestamp fromSystemTime(long systemTime) {
          //initializing with -1 so that addTicks resets it to 0
          return new HybridTimestamp(systemTime, -1);
      }
  
      public HybridTimestamp max(HybridTimestamp other) {
          if (this.getWallClockTime() == other.getWallClockTime()) {
              return this.getTicks() > other.getTicks()? this:other;
          }
          return this.getWallClockTime() > other.getWallClockTime()?this:other;
      }
  
      public long getWallClockTime() {
          return wallClockTime;
      }
  
      public HybridTimestamp addTicks(int ticks) {
          return new HybridTimestamp(wallClockTime, this.ticks + ticks);
      }
  
      public int getTicks() {
          return ticks;
      }
  
      @Override
      public int compareTo(HybridTimestamp other) {
          if (this.wallClockTime == other.wallClockTime) {
              return Integer.compare(this.ticks, other.ticks);
          }
          return Long.compare(this.wallClockTime, other.wallClockTime);
      }

混合時鐘可以用與 Lamport 時鐘 版本完全相同的方式使用。每個伺服器都持有混合時鐘的實例。

欲了解更多詳細資訊,請參閱 oreilly.com 上線上電子書的 第 23 章

此模式是 分散式系統模式 的一部分

2023 年 11 月 23 日