AnsweredAssumed Answered

StrongUuidGenerator not thread safe

Question asked by marcus1 on May 14, 2012
Latest reply on May 15, 2012 by marcus1
Activiti's StrongUuidGenerator uses fasterxml's TimeBasedGenerator to generate unique ids. Today, during performance testing, I encountered a lot of collisions. Diving in the sources I found that TimeBasedGenerator is, contrary to what the documentation suggests, not thread safe.

This can be easily demonstrated using the following test, which will find a collision even with just 2 threads:

final TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
final Set<UUID> ids = new HashSet<UUID>();

Runnable r = new Runnable() {
   public void run() {
      for (int i = 0; i < 10000; i++) {
         UUID id = timeBasedGenerator.generate();
         synchronized (ids) {
            if (!ids.add(id)) {
               throw new RuntimeException("Id not unique: " + id);
            }
         }
      }
   }
};

ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 2; i++) {
   executorService.execute(r);
}
executorService.shutdown();
Synchronizing on timeBasedGenerator resolves this.

The root problem is in TimeBasedGenerator, where _uuidBytes is shared between calls to generate().

Edit: I may be using an old version of JUG…

Outcomes