Search code examples
javamultithreadinguuid

Same UUID being generated in multi-threaded application


I am using the UUID.randomUUID().toString() to append a unique value to a string that is ultimately stored in the database and has unique constraint on it

But because my application is multi-threaded the execution happens at the same time of UUID generation and ultimately the same UUID is appended to the string and persistence fails.

Is there a better way to generate random string i.e. a fail-safe method.

I tried debugging and when I paused the other threads and let them go one by one then it worked fine.

I am currently using the following code to make it more random but i do not like this approach.

Random r = new Random();
List<Integer> uniqueNUmbers = new ArrayList<>();
for (int i=0;i<10;i++) {
int x=r.nextInt(9999);
while (uniqueNumbers.contains(x))
x=r.nextInt(9999);
uniqueNumbers.add(x);
} 
String string = String.format("%04d", uniqueNumbers.get(0));

string = uuid + string;

But this is like a hacky code. And I dont like this.

Does any one know a fail-proof method to actually geenrate a random string.


Solution

  • You can synchronize uuid-generation method, and/or you can pregen uuid pool and generate more identificators in one thread when pool starts to deplete.