Reputation: 338
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
Upvotes: 2
Views: 1777
Reputation: 21773
Yes, start with a random 32 bit integer and increment it.
Anything else will be too demanding as you scale up (e.g. 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
Upvotes: 5
Reputation: 1
you can try like this
private static byte[] synhead = {(byte)0xAA,0x55,0x7E,0x0B};
Upvotes: 0