I am using UUID.randomUUID (). toString () to add a unique value to a string that is ultimately stored in the database and has a unique restriction on it
But since my application is multithreaded, the execution happens simultaneously with the generation of the UUIDs, and ultimately the same UUID is added to the string, and the persistence fails.
Is there a better way to generate a random string, i.e. a fault tolerant method.
I tried debugging, and when I paused the other threads and released them one by one, it worked fine.
I am currently using the following code to make it more random, but I don't 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 hacked code. And I do not like it.
- .