nimo23 :
I want to generate an unique ID within my application which can be used as a primary key for my database. The ID should be created by the application (and not by the database). I am wondering which method should I better use for that:
version 1:
// maybe faster and more memory friendly than version 2
// but what about collisions?
var uniqueId = ThreadLocalRandom.current().nextInt()
or version 2:
var uniqueId = UUID.randomUUID().toString()
or version 3:
// maybe the same as version 1
var uniqueId = new SecureRandom().nextInt()
or anything better?
ciamej :
Both versions 1 and 3 will produce collisions, because there are only 2^32
different int
's. You need to calculate the probability yourself.
Regular UUIDs (version 2) are also random, but there is 2^128
of them, which means the chances of a collision are negligible.