Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java for loop executes too fast gives System.currentTimeMillis() duplicate

Java: I have a problem using System.currentTimeMillis() function

i am using System.currentTimeMillis() to generate unique values in foor loop problem is loop executes too fast and System.currentTimeMillis() gives me duplicate values.

How can i generate for sure unique values.

for(int a=0;a<=10;a++){
System.out.println(System.currentTimeMillis())
}

I also tried following but it is also not generaet to generate unique number

System.currentTimeMillis()+Math.random()
like image 545
d-man Avatar asked Dec 03 '22 08:12

d-man


2 Answers

why don't you use System.nanoTime() instead?

like image 180
Liv Avatar answered Dec 06 '22 09:12

Liv


Why don't you use a UUID library to generate unique identifiers (already there in the JDK http://download.oracle.com/javase/6/docs/api/java/util/UUID.html).

Or for a more simple approach: append a static counter

like image 37
leifg Avatar answered Dec 06 '22 09:12

leifg