cancel
Showing results for 
Search instead for 
Did you mean: 

StrongUuidGenerator not thread safe

marcus1
Champ in-the-making
Champ in-the-making
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…
1 REPLY 1

marcus1
Champ in-the-making
Champ in-the-making
Okay, I was indeed using an old version of JUG: 3.1.0. With 3.1.3 it's working fine. Oops, my mistake Smiley Happy