How to generate unique positive Long using UUID

后端 未结 6 1184
旧巷少年郎
旧巷少年郎 2020-12-03 02:21

I have a requirement to generate unique Long ids for my database primary key column.

I thought i can use UUID.randomUUID().getMostSignificantBits()

6条回答
  •  醉话见心
    2020-12-03 03:16

    As the others have written, long does not have enough space for a unique number. But in many cases a number may be unique enough for a specific use. For example, a timestamp with the nanosecond precision is often good enough. To get it, shift the current milliseconds 20 bits left to allocate space for nanoseconds and then overlay it with the nanoseconds:

    (System.currentTimeMillis() << 20) | (System.nanoTime() & ~9223372036854251520L);
    

    The nano & ~9223372036854251520L part takes the current nanoseconds and sets the first 44 bytes to 0, leaving only the right 20 bits which represent nanoseconds up to one millisecond (999999 nanos) It is the same as:

    nanoseconds & ~1111111111111111111111111111111111111111111100000000000000000000
    

    Side note: nanoseconds should not be used to represent the current time because their starting point is not fixed in time and because they are recycled when they reach the maximum.

    You can use any other bit manipulation. It is usually good to take into account the current time and something else such as the current thread id, process id, ip.

提交回复
热议问题