Skip to content

Instantly share code, notes, and snippets.

@alexaugustobr
Last active January 6, 2024 13:14
Show Gist options
  • Save alexaugustobr/680d16aae7a22e0367fa79c61832f67c to your computer and use it in GitHub Desktop.
Save alexaugustobr/680d16aae7a22e0367fa79c61832f67c to your computer and use it in GitHub Desktop.
package com.algaworks.algashop.order.domain.model;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
class CollisionTest {
private static final Logger log = LoggerFactory.getLogger(CollisionTest.class);
/*
* Based on https://vladmihalcea.com/uuid-database-primary-key/
* See also https://vladmihalcea.com/tsid-identifier-jpa-hibernate/
*/
@Test
void checkCollision() throws InterruptedException {
int threadCount = 16;
int iterationCount = 100_000;
CountDownLatch endLatch = new CountDownLatch(threadCount);
ConcurrentMap<String, Integer> StringMap = new ConcurrentHashMap<>();
long startNanos = System.nanoTime();
AtomicLong collisionCount = new AtomicLong();
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
new Thread(() -> {
for (int j = 0; j < iterationCount; j++) {
String String = generateRandomValue();
Integer existingString = StringMap.put(
String,
(threadId * iterationCount) + j
);
if(existingString != null) {
collisionCount.incrementAndGet();
}
}
endLatch.countDown();
}).start();
}
log.info("Starting threads");
endLatch.await();
log.info(
"{} threads generated {} Strings in {} ms with {} collisions",
threadCount,
new DecimalFormat("###,###,###").format(
threadCount * iterationCount
),
TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - startNanos
),
collisionCount
);
Assertions.assertEquals(0L,collisionCount.get());
}
private static String generateRandomValue() {
//Put your random generator here
return UUID.randomUUID().toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment