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.

+1


source to share


3 answers


Just copy the bits you don't need:



return java.util.UUID.randomUUID().getLeastSignificantBits();

      

+3


source


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.

+1


source


If unique in one 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++;
    }
}

      

+1


source







All Articles