1

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.

Regards

sherybedrock
  • 111
  • 3
  • 11

2 Answers2

3
    int[] result = new Random().ints(10_000_000, 100_000_000)
            .distinct()
            .limit(8)
            .toArray();

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I'm not sure how exactly this will be achieved through db // @Joop Eggen – sherybedrock Feb 17 '20 at 13:32
  • I even do not know what those 8 numbers are for. But storing them in a database allows access in every clustered server. Again I do not know your constellation. – Joop Eggen Feb 17 '20 at 14:05
0

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

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

for(...) {
    rndgen.nexbytes(rnd);
    ...
}

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 {
            break;
        }
    }
    // 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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252