0

Here's the source code.

But it seems each time when the users invoke getInstance() it will create a new instance.

I should have misunderstood something.

K.Miao
  • 811
  • 7
  • 21

1 Answers1

2

The source doesn't contradict your observation:

public static final KeyGenerator getInstance(String algorithm)
        throws NoSuchAlgorithmException {
    if (algorithm == null) {
        throw new NullPointerException("algorithm == null");
    }
    Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
    return new KeyGenerator((KeyGeneratorSpi) sap.spi, sap.provider, algorithm);
}

What might be a singleton is the SpiAndProvider returned by ENGINE#getInstance. If you look further into the implementation it's not surprising that there is a new instance each time you call getInstance because KeyGenerator has instance members, initiated with the parameters you pass with a call.

Lothar
  • 5,323
  • 1
  • 11
  • 27