Home » Java » Generate unique integer with 8 digits in java-Exceptionshub

Generate unique integer with 8 digits in java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I’m trying to figure how to approach with generating unique integer with 8 digits in java. The biggest problem is that it gives you a limited permutation, and also the clustered env. Any suggestion is welcome.


How to&Answers:
    int[] result = new Random().ints(10_000_000, 100_000_000)

8 digits starts with 10_000_000 upto inclusive 99_999_999.
The large range means that duplicates are rear, so the internal looping will rarely be idle, have conflicting duplicates.

Clustered usage: easiest is to use a database.


If you only need a limited number of values, you could try Random:

byte[] rnd = new byte[1];
Random rndgen = new Random():

for(...) {

But as one byte can only hold 256 different values the collision risk if high.

If you have one single emitter, just use the natural sequence

boolean first = true;
byte i = 0;
for(;;) {
    if(i == 0) {
        if (first):
            first = false;
        else {
    // use i
    i +== 1;

If you have a limited number of emitters, give each a subrange. For example for 4 nodes, each node will have a sequence of 64 values.

On a more complex use case, the only possible way is to dedicate a master that will manage the sequence 0-255: each node asks it for next value.