UUID to unique integer id?

前端 未结 6 757
悲哀的现实
悲哀的现实 2021-01-01 08:37

I was wondering what the easiest way to convert a UUID to a unique integer would be? I have tried using the hash code but people tell me that it is not going to always be un

6条回答
  •  抹茶落季
    2021-01-01 09:07

    Answering the How can I have a unique application wide Integer:

    If it needs to be unique even after restarts or if you application is clustered you may use a Database sequence.

    If it just needs to be unique during the runtime use a static AtomicInteger.

    EDIT (example added):

    public class Sequence {
    
      private static final AtomicInteger counter = new AtomicInteger();
    
      public static int nextValue() {
        return counter.getAndIncrement();
      }
    }
    

    Usage:

    int nextValue = Sequence.nextValue();
    

    This is thread safe (different threads will always receive distinct values, and no values will be "lost")

提交回复
热议问题