3

By looking at the source code of OpenJDK 13, I've stumbled upon this perplexing comment in the ImmutableCollections internal class that holds the implementations of many immutable collections generated by List.of(), Set.of(), and Map.of():

class ImmutableCollections {
    /**
     * A "salt" value used for randomizing iteration order. This is initialized once
     * and stays constant for the lifetime of the JVM. It need not be truly random, but
     * it needs to vary sufficiently from one run to the next so that iteration order
     * will vary between JVM runs.
     */
    static final int SALT;
    static {
        long nt = System.nanoTime();
        SALT = (int)((nt >>> 32) ^ nt);
    }

    ...
}

The static field SALT is then used in implementations of Set and Map iterators to determine iteration order. Why would it be necessary, or even desirable to have a randomized iteration order for each JVM run when iterating these types of collections?

farsil
  • 955
  • 6
  • 19
  • @JBNizet you have a source for that claim? – Turing85 Jan 11 '20 at 14:52
  • Compare this to `HashSet`, which just says "doesn't guarantee" iteration order. Some people might iterate over it without reading that, and finds that the order just so happens to be exactly the same as insertion order. They might then come to the wrong conclusion. – Sweeper Jan 11 '20 at 14:53
  • @JBNizet I'd just copy paste that to an answer tbh. – ruohola Jan 11 '20 at 14:53
  • 1
    @Turing85 see the duplicate (especially the start of the quote in the question itself) – JB Nizet Jan 11 '20 at 14:55
  • @JBNizet Thanks! Didn't see that the question was closed in the mean time =) – Turing85 Jan 11 '20 at 14:56

0 Answers0