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?