Reputation: 394
I have a Spring 3 service method that I want to return a PrivateKey/PublicKey keyPair from - is it thread safe to have the KeyPairGenerator as an instance level variable in the service to avoid having to call KeyPairGenerator.getInstance(algo) and initializing it in the method call or should I keep the KeyPairGenerator local to the service method and call .getInstance(algo) and .initialize(...) for each method invocation, ie:
public KeyPair getKeyPair() throws ... {
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algo);
keyGenerator.initialize(1024);
return (keyGenerator.genKeyPair());
}
or
public KeyPair getKeyPair() throws ... {
// use instance level keyGenerator that has been previously initialized
return (keyGenerator.genKeyPair());
}
Are there possible concurrency issues with the second approach? Is the performance penalty significant with the first approach?
Upvotes: 3
Views: 1125
Reputation: 340733
This question is not really Spring-related. I believe you are talking about KeyPairGenerator
. The JavaDoc is not saying anything about thread safety, but there is a comment in the source code:
// * although not specified, KeyPairGenerators could be thread safe,
// so we make sure we do not interfere with that
Well, "could be thread safe" means absolutely nothing to me, especially after looking at access to keypairgenerator may not be thread safe issue:
the concurrency properties of the key pair generator are spi specific and may not be thread safe. this can cause failures which hang the front end.
So my advice would be to create new instance on every call, or pool them.
Upvotes: 4