Skip to content

Commit

Permalink
Check more timestamps and they are increasing #646
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-lawrey committed Apr 10, 2024
1 parent 60a9f33 commit d8dda53
Showing 1 changed file with 31 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
Expand All @@ -46,26 +44,34 @@ public void setUp() {

@Test
public void shouldProvideUniqueTimeAcrossThreads() throws InterruptedException {
final Set<Long> timeSet = ConcurrentHashMap.newKeySet();
final int numThreads = 100;
final int numIterations = 1_000;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
CountDownLatch latch = new CountDownLatch(numThreads);

for (int i = 0; i < numThreads; i++) {
final Set<Long> allGeneratedTimestamps = ConcurrentHashMap.newKeySet();
final int numberOfThreads = 50;
final int factor = 50;
final int iterationsPerThread = 500;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads * factor);

for (int i = 0; i < numberOfThreads * factor; i++) {
executor.execute(() -> {
for (int j = 0; j < numIterations; j++) {
List<Long> threadTimeSet = new ArrayList<>(iterationsPerThread);
long lastTimestamp = 0;
for (int j = 0; j < iterationsPerThread; j++) {
setTimeProvider.advanceNanos(j);
timeSet.add(timeProvider.currentTimeMicros());
long currentTimeMicros = timeProvider.currentTimeMicros();
threadTimeSet.add(currentTimeMicros);
assertTrue("Timestamps should always increase", currentTimeMicros > lastTimestamp);
lastTimestamp = currentTimeMicros;
}
allGeneratedTimestamps.addAll(threadTimeSet);
latch.countDown();
});
}

latch.await();
executor.shutdown();

assertEquals("All timestamps should be unique", numThreads * numIterations, timeSet.size());
assertEquals("All timestamps across all threads and iterations should be unique",
numberOfThreads * iterationsPerThread * factor, allGeneratedTimestamps.size());
}

@Test
Expand Down Expand Up @@ -109,6 +115,18 @@ public void currentTimeMicrosShouldBeCorrect() {
}
}

@Test
public void currentTimeMicrosShouldBeCorrectBackwards() {
long lastTimeMicros = 0;

for (int i = 0; i < 4_000; i++) {
setTimeProvider.advanceNanos(-i);
long currentTimeMicros = timeProvider.currentTimeMicros();
assertTrue("Microsecond timestamps must increase", currentTimeMicros > lastTimeMicros);
lastTimeMicros = currentTimeMicros;
}
}

@Test
public void currentTimeNanosShouldBeCorrect() {
long lastTimeMicros = 0;
Expand Down

0 comments on commit d8dda53

Please sign in to comment.