0

I was looking at the java.util.Random class and found this:

private static long seedUniquifier() {
    // L'Ecuyer, "Tables of Linear Congruential Generators of
    // Different Sizes and Good Lattice Structure", 1999
    for (;;) {
        long current = seedUniquifier.get();
        long next = current * 181783497276652981L;
        if (seedUniquifier.compareAndSet(current, next))
            return next;
    }

Is there any reason for that loop to be there ?

Ced
  • 15,847
  • 14
  • 87
  • 146
  • 1
    To keep going until the CAS returns true? – chrylis -cautiouslyoptimistic- Sep 19 '15 at 01:03
  • @chrylis oh s*. I assumed the loop would run only once because there was no condition. so it's like a while(true). I should have test it but for some reason I didnt second guess myself. – Ced Sep 19 '15 at 01:05
  • There is no empty loop here. There is an empty `for` statement with no initial statement, while-condition, or increment-statement. Not the same thing. – user207421 Sep 19 '15 at 01:05
  • 1
    in java8, this code can be rewritten as `return seedUniquifier.updateAndGet(current->current*181783497276652981L);` -- the meaning is more clear - atomically multiply the value. – ZhongYu Sep 19 '15 at 01:13

2 Answers2

1

The field seedUniquifier is an AtomicInteger, and the compareAndSet instruction is used to prevent thread collisions by verifying the expected contents of a variable and changing it in a single operation.

Based on the description in the Javadoc:

This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

It looks like the purpose of the uniquifier is to help ensure that if two threads both try to create a new Random() at the same time, they won't both end up with the same seed value (and thus sequence of output); the for loop tells the constructor that if it finds a collision (the compareAndSet is false), then it should keep trying. In normal circumstances, it'll return instantly.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

for(;;) is an infinity cycle, which should contain break or return or you'll got an unreachable statement compile error.

serhii
  • 1,135
  • 2
  • 12
  • 29