SecureRandom.generateSeed() and unnecessary garbage

Chris Hennick chrishennick1 at gmail.com
Wed Oct 16 03:22:14 UTC 2019


While working on BetterRandom <https://github.com/Pr0methean/BetterRandom>
tonight, I was reminded that a quirk of SecureRandom's API creates
unnecessary garbage in my use case:

public class SecureRandomSeedGenerator implements SeedGenerator, Serializable {
  private final SecureRandom source;

  @Override public void generateSeed(final byte[] output) {
    System.arraycopy(source.generateSeed(output.length), 0, output, 0,
output.length);
  }
}

The garbage in this case is the original array returned by
source.generateSeed(). SeedGenerator.generateSeed()'s only warm callsites
when used as I recommend (which are
https://github.com/Pr0methean/BetterRandom/blob/bdd596d25497776156b8c87ab749e00c8b2b8bd0/betterrandom/src/main/java/io/github/pr0methean/betterrandom/seed/RandomSeederThread.java#L226)
are specifically designed to use existing array instances, so that
reseeding produces the minimum of garbage.

For the garbage creation to be eliminated, I believe
source.generateSeed(output.length) would at least have to be inlined
(recursing down into the SecureRandomSpi), followed by escape analysis.
Even then, eliminating the arraycopy is probably somewhere around the
bleeding edge of optimization (although the arrays are likely to be short,
and often all the same length). It's worth noting that
SeedGenerator.generateSeed() is likely to be trimorphic at the warm
call-sites because of
https://github.com/Pr0methean/BetterRandom/blob/6df10c5b6e8ec24dea4275bf2b487dd9aecdc369/betterrandom/src/main/java/io/github/pr0methean/betterrandom/seed/DefaultSeedGenerator.java#L42-L45
.

Should SecureRandom maybe have an API that can write a seed to an existing
byte array, garbagelessly when possible?

Sincerely,
Chris Hennick


More information about the jdk-dev mailing list