How can I collect bits into a long one to create a unique identifier?
I would like to write a utility that will provide me with a relatively unique ID in Java. Something very simple like x bits from timestamp + y bits from random number.
So how would I implement the following method:
long getUniqueID()
{
long timestamp = System.currentTimeMillis();
long random = some random long
...
return id;
}
BONUS
Any suggestions for other readily available information that I could use to form my ID?
note: I know the GUID, and I know that Java has a UUID class, but I don't want the length to be 128 bits.
source to share
What you are trying to do is create one that concatenates two long values โโinto one long value. In this case, the uniformity of the hash function will be of paramount importance, since conflicts in the generated unique identity values โโare unacceptable. However, if you can compare hash values โโwith previously generated identifiers, then conflicts can be resolved by changing the hash until a collision occurs.
For example, you can take a timestamp and do exclusive or (using the Caret operator ^ in Java) with a random value. If a collision is found, add it to the result.
source to share