简体   繁体   中英

strategy to create 4 bytes unique Id in java

Our java application has a 4 bytes size restriction to hold unique id.

We are forced to implement a strategy to create unique ids which are 4 bytes in size.

Does any one know a strategy to create it

Yes, start with a random 32 bit integer and increment it.

Anything else will be too demanding as you scale up (eg if you have 1 billion already created ids and need to randomly generate a new one, you have to have a 1 billion entry table to check for existence inside... ouch!).

But if it absolutely has to be random and unique, the two strategies you can take are:

1) Have a big HashSet of every id used so far and check for existence in the set whenever you generate a new random ID. If it is, discard and try again.

2) Store all randomly used IDs in the database, and do a SELECT to see if your newly generated random ID exists. If it does, discard and try again.

If the unique ID was larger, you could use a Guid (also known as uuid), which are generated large enough and in such a way that you'll never see two Guids have the same value ever, anywhere, without needing to check.

For Guids/UUIDs in java, see http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html

我认为int可以满足您的要求。

你可以这样试试

private static byte[] synhead = {(byte)0xAA,0x55,0x7E,0x0B};

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