简体   繁体   中英

How can I assemble bits into a long to create a unique ID?

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.

只需剪掉不需要的部分:

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

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.

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++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM