简体   繁体   中英

Why mongodb java driver uses random bytes instead of machine id in ObjectId?

Many people say that ObjectId consist of:

  • a 4-byte value representing the seconds since the Unix epoch (which will not run out of seconds until the year 2106)
  • a 3-byte machine identifier (usually derived from the MAC address),
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

And if the objectId contains all these elements then it's guaranteed that all ids are unique across the cluster. But the docs say that there're no machine and process ids and the objectId contains just a random value ( https://docs.mongodb.com/manual/reference/method/ObjectId )

I looked in the java mongo driver ObjectId generation and found the evidence:

SecureRandom secureRandom = new SecureRandom();
RANDOM_VALUE1 = secureRandom.nextInt(0x01000000);
RANDOM_VALUE2 = (short) secureRandom.nextInt(0x00008000);

// ...

private ObjectId(final int timestamp, final int counter, final boolean checkCounter) {
    this(timestamp, RANDOM_VALUE1, RANDOM_VALUE2, counter, checkCounter);
}

So, it's possible (ok, the probability is really low, but still) that two machines generate the same random numbers and all the consequently generated ids will have clashes very probably. Why such decision has been made? Is it still perfectly unique, but I don't understand something? Thanks!

Edit: Well, the purpose of the question is: should I implement the retrieving of MAC address and processId and generate ObjectId by myself or leave random 5 bytes number, because there's no difference?

Why mongodb java driver uses random bytes instead of machine id in ObjectId?

This behavior is mandated by the ObjectId specification .

The same document provides the rationale :

Random Value: Originally, this field consisted of the Machine ID and Process ID fields. There were numerous divergences between drivers due to implementation choices, and the Machine ID field traditionally used the MD5 hashing algorithm which can't be used on FIPS compliant machines. In order to allow for a similar behaviour among all drivers and the MongoDB Server, these two fields have been collated together into a single 5-byte random value, unique to a machine and process.

You should not need to implement ObjectId generation, as all MongoDB drivers necessarily need to provide this functionality.

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