Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring service method thread safety

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?

like image 484
jc1001 Avatar asked Apr 02 '26 03:04

jc1001


1 Answers

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.

like image 50
Tomasz Nurkiewicz Avatar answered Apr 08 '26 04:04

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!