简体   繁体   English

策略在java中创建4​​个字节的唯一ID

[英]strategy to create 4 bytes unique Id in java

Our java application has a 4 bytes size restriction to hold unique id. 我们的java应用程序有4个字节的大小限制来保存唯一ID。

We are forced to implement a strategy to create unique ids which are 4 bytes in size. 我们被迫实施一个策略来创建大小为4字节的唯一ID。

Does any one know a strategy to create it 有没有人知道创建它的策略

Yes, start with a random 32 bit integer and increment it. 是的,从一个随机的32位整数开始并递增它。

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!). 当你扩展时,任何其他东西都会过于苛刻(例如,如果你有10亿个已经创建的ID并且需要随机生成一个新的,你必须有一个10亿的条目表来检查内部存在...哎哟!)。

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. 1)到目前为止,使用每个id的大HashSet ,并在生成新的随机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. 2)将所有随机使用的ID存储在数据库中,并执行SELECT以查看是否存在新生成的随机ID。 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. 如果唯一ID较大,您可以使用Guid(也称为uuid),这些Guid生成得足够大,以至于您永远不会看到两个Guids在任何地方都具有相同的值,而无需检查。

For Guids/UUIDs in java, see http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html 有关Java中的Guids / UUID,请参阅http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html

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

你可以这样试试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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