Generating a globally unique identifier in Java

前端 未结 6 1896
广开言路
广开言路 2020-11-29 04:32

Summary: I\'m developing a persistent Java web application, and I need to make sure that all resources I persist have globally unique identifiers to prevent

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 04:57

    If it needs to be unique per PC: you could probably use (System.currentTimeMillis() << 4) | (staticCounter++ & 15) or something like that.

    That would allow you to generate 16 per ms. If you need more, shift by 5 and and it with 31...

    if it needs to be unique across multiple PCs, you should also combine in your primary network card's MAC address.

    edit: to clarify

    private static int staticCounter=0;
    private final int nBits=4;
    public long getUnique() {
        return (currentTimeMillis() << nBits) | (staticCounter++ & 2^nBits-1);
    }
    

    and change nBits to the square root of the largest number you should need to generate per ms.

    It will eventually roll over. Probably 20 years or something with nBits at 4.

提交回复
热议问题