Skip to content

Instantly share code, notes, and snippets.

@jadamcrain
Created August 11, 2012 11:12
Show Gist options
  • Save jadamcrain/3323860 to your computer and use it in GitHub Desktop.
Save jadamcrain/3323860 to your computer and use it in GitHub Desktop.
Looking for UUID collisions in Java
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);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment