tags:

views:

257

answers:

3

I would like to write a utility that will provide me with a relatively unique ID in Java. Something pretty 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 easily obtainable information I could use to form my ID?

note: I am aware of GUIDs and I know Java has a UUID class, but I don't want something that is 128 bits long.

+1  A: 

What you are trying to do is create a hash function that combines two long values into a single long value. In this case, the uniformity of the hash function will be of utmost importance since collisions in created unique ID values are unacceptable. However, if you can compare hash values to previously created identifiers, then collisions can be resolved by modifying the hash until no collision occurs.

For example, you could take the time stamp and perform an exclusive-or (using the caret ^ operator in Java) with the random value. If a collision is detected, then add one to the result.

Judge Maygarden
care to elaborate?
carrier
OK, I elaborated ;)
Judge Maygarden
+2  A: 

Just clip the bits you don't need:

return java.util.UUID.randomUUID().getLeastSignificantBits();
phihag
A: 

If unique in the same JVM is enough then something like this should do the job.

public class UniqueID {
  static long current= System.currentTimeMillis();
  static public synchronized long get(){
    return current++;
    }
}
RealHowTo