我有一个 Spring 3 服务方法,我想从中返回一个 PrivateKey/PublicKey keyPair - 将 KeyPairGenerator 作为服务中的实例级变量是否是线程安全的,以避免必须调用 KeyPairGenerator.getInstance(algo) 和在方法调用中初始化它,或者我应该将 KeyPairGenerator 保留在服务方法的本地并为每个方法调用调用 .getInstance(algo) 和 .initialize(...),即:
public KeyPair getKeyPair() throws ... {
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algo);
keyGenerator.initialize(1024);
return (keyGenerator.genKeyPair());
}
或
public KeyPair getKeyPair() throws ... {
// use instance level keyGenerator that has been previously initialized
return (keyGenerator.genKeyPair());
}
第二种方法是否可能存在并发问题?第一种方法的性能损失是否显着?
最佳答案
这个问题与 Spring 无关。我相信你在谈论KeyPairGenerator
. JavaDoc 没有提及任何关于线程安全的内容,但有一条评论 in the source code :
// * although not specified, KeyPairGenerators could be thread safe,
// so we make sure we do not interfere with that
好吧,“可能是线程安全的”对我来说毫无意义,尤其是在查看了 access to keypairgenerator may not be thread safe 之后问题:
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.
所以我的建议是在每次调用时创建新实例,或者 pool them .
关于java - Spring服务方法线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219986/