ハイブリッドクロック
日付と時間のバージョンのように、システムタイムスタンプと論理タイムスタンプの組み合わせを使用します。これにより、バージョンを並べ替えることができます。
問題
ランポートクロックがバージョン値のバージョンとして使用されると、クライアントはこの特定のバージョンが格納された実際の日時を知りません。クライアントは、1、2、3などの整数ではなく、01-01-2020などの日付と時間を使用してバージョンにアクセスするほう便利です。
解決策
ハイブリッド論理クロックは、単一の整数のように単調に増加するバージョンを作成する方法を提供しますが、実際の日付と時間との関係もあります。ハイブリッドクロックは、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);
}
ハイブリッドクロックは、ランポートクロックのバージョンとまったく同じ方法で使用できます。各サーバーはハイブリッドクロックのインスタンスを保持します。
詳細については、oreilly.comのオンライン電子書籍の第23章を参照してください。
このパターンは分散システムの設計パターンの一部です。
2023年11月23日

