Skip to content

Commit

Permalink
[Java] Increment sequence if the clock is not advancing or going back…
Browse files Browse the repository at this point in the history
…wards.
  • Loading branch information
vyazelenko committed May 15, 2024
1 parent 76d7d5a commit 52f9c6d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public long nextId()
return newTimestampSequence | nodeBits;
}
}
else if (timestampMs == oldTimestampMs)
else
{
final long oldSequence = oldTimestampSequence & maxSequence;
if (oldSequence < maxSequence)
Expand All @@ -237,11 +237,6 @@ else if (timestampMs == oldTimestampMs)
}
}
}
else
{
throw new IllegalStateException(
"clock has gone backwards: timestampMs=" + timestampMs + " < oldTimestampMs=" + oldTimestampMs);
}

if (Thread.currentThread().isInterrupted())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ void shouldAdvanceTimestamp()
}

@Test
void shouldDetectClockGoingBackwards()
void shouldAdvanceSequenceWhenClockIsGoingBackwards()
{
final long nodeId = 7;
final long timestampOffset = 0;
Expand All @@ -215,10 +215,18 @@ void shouldDetectClockGoingBackwards()
NODE_ID_BITS_DEFAULT, SEQUENCE_BITS_DEFAULT, nodeId, timestampOffset, clock);
clock.update(7);

idGenerator.nextId();
final long firstId = idGenerator.nextId();
final long firstTimestamp = clock.time();
assertEquals(firstTimestamp, idGenerator.extractTimestamp(firstId));
assertEquals(nodeId, idGenerator.extractNodeId(firstId));
assertEquals(0L, idGenerator.extractSequence(firstId));

clock.update(3);
assertThrows(IllegalStateException.class, idGenerator::nextId);
clock.update(4);

final long secondId = idGenerator.nextId();
assertEquals(firstTimestamp, idGenerator.extractTimestamp(secondId));
assertEquals(nodeId, idGenerator.extractNodeId(secondId));
assertEquals(1L, idGenerator.extractSequence(secondId));
}

@Test
Expand Down

0 comments on commit 52f9c6d

Please sign in to comment.