Java: Unique 10 digit ID

后端 未结 4 1744
渐次进展
渐次进展 2020-12-13 15:57

I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:

  • Only Numeric
  • Maximum 10 digits
  • Possible to create up
相关标签:
4条回答
  • 2020-12-13 16:19

    This may be a crazy idea but its an idea :).

    • First generate UUID and get a string representation of it with java.util.UUID.randomUUID().toString()
    • Second convert generated string to byte array (byte[])

    • Then convert it to long buffer: java.nio.ByteBuffer.wrap( byte digest[] ).asLongBuffer().get()

    • Truncate to 10 digits

    Not sure about uniqueness of that approach tho, I know that you can rely on uniqueness of UUIDs but haven't checked how unique are they converted and truncated to 10 digits long number.

    Example was taken from JavaRanch, maybe there is more.

    Edit: As you are limited to 10 digits maybe simple random generator would be enough for you, have a look into that quesion/answers on SO: Java: random long number in 0 <= x < n range

    0 讨论(0)
  • 2020-12-13 16:25
    private static AtomicReference<Long> currentTime = new AtomicReference<>(System.currentTimeMillis());
    
    public static Long nextId() {
        return currentTime.accumulateAndGet(System.currentTimeMillis(), (prev, next) -> next > prev ? next : prev + 1) % 10000000000L;
    }
    
    0 讨论(0)
  • 2020-12-13 16:27

    This is a small enhancement to yours but should be resilient.

    Essentially, we use the current time in milliseconds unless it hasn't ticked since the last id, in which case we just return last + 1.

    private static final long LIMIT = 10000000000L;
    private static long last = 0;
    
    public static long getID() {
      // 10 digits.
      long id = System.currentTimeMillis() % LIMIT;
      if ( id <= last ) {
        id = (last + 1) % LIMIT;
      }
      return last = id;
    }
    

    As it is it should manage up to 1000 per second with a comparatively short cycle rate. To extend the cycle rate (but shorten the resolution) you could use (System.currentTimeMillis() / 10) % 10000000000L or (System.currentTimeMillis() / 100) % 10000000000L.

    0 讨论(0)
  • 2020-12-13 16:35

    What means that it has to be unique? Even across more currently running instances? It break your implementation.

    If it must be unique across universe, the best solution is to use UUID as it's mathematically proven identifier generator as it generates unique value per universe. Less accurate number brings you collisions.

    When there is only one concurrent instance, you can take current time in millis and solve 10ms problem using incrementation. If you sacrifice proper number of last positions in the number you can get many number within one milliseconds. I would than define the precision - I mean how much unique numbers do you need per seconds. You will solve the issue without any persistence using this approach.

    0 讨论(0)
提交回复
热议问题