public
Created

Looking for UUID collisions in Java

  • Download Gist
UUIDTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
import java.util.HashSet;
import java.util.LinkedList;
import java.util.UUID;
 
public class UUIDTest {
 
public static void main(String[] args) throws InterruptedException {
HashSet<UUID> set = new HashSet<UUID>(1000);
LinkedList<Thread> threads = new LinkedList<Thread>();
for(int i=0; i<128; ++i) {
Thread t = new UUIDGenThread(set, 100000);
t.start();
threads.push(t);
}
for(Thread t: threads) t.join();
 
System.out.println("Set size: " + set.size());
 
}
 
static class UUIDGenThread extends Thread {
 
private HashSet<UUID> set;
private int numUUIDS;
 
public UUIDGenThread(HashSet<UUID> set, int numUUIDS) {
this.set = set;
this.numUUIDS = numUUIDS;
}
 
public void run() {
for(int i=0; i<numUUIDS; ++i) {
synchronized (set) {
UUID uuid = UUID.randomUUID();
if(set.contains(uuid)) System.out.println("Collision: " + uuid);
else set.add(uuid);
}
}
}
 
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.