SecureRandom.generateSeed() and unnecessary garbage

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

While working on 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,

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
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

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

Chris Hennick

More information about the jdk-dev mailing list