title: Spring service method thread safety
body: <p>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:</p>
  
  <pre><code>public KeyPair getKeyPair() throws ... {
      KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algo);
      keyGenerator.initialize(1024);
      return (keyGenerator.genKeyPair());
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>public KeyPair getKeyPair() throws ... {
      // use instance level keyGenerator that has been previously initialized
      return (keyGenerator.genKeyPair());
  }
  </code></pre>
  
  <p>Are there possible concurrency issues with the second approach?  Is the performance penalty significant with the first approach?</p>