Adding security provider multiple times in Java application

We have a Java application where the job needs to run every 5 minutes. This task has a security component that runs every time on every execution:

java.security.Security
            .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

      

My questions:

  • Do you need to add a security provider to your application multiple times? Does it serve any purpose? It doesn't make sense to me and adding it once should be enough.
  • Is he a candidate for a potential memory leak in your application?

To clarify, I want to programmatically install the Bouncy Castle security provider in my application, not statically via the JRE. IMO, adding that the Bouncy Castle security provider once in the application is enough and I don't have to do it multiple times.

+3


source to share


1 answer


According to the addProvider

javadoc
:

Return:
the preference position to which the provider was added, or -1 if the provider was not added because it is already set

addProvider

already checks if the provider is installed, so even if you have multiple calls in the application, it will just be added once. And after you add it, it stays there until the JVM stops (or if someone calls removeProvider

).

Of course, you can optimize it and put only one call in the main class (some class that you know it always loads when the application starts), but I wouldn't bother with that.



I've worked with systems that had multiple calls addProvider

in different parts (because they could be called in any order and were independent of each other), they all run in the same JVM, and it never got any memory leaks. Of course, this is just my business, but I don't know what is causing the leaks.


If you only want to call addProvider

if the provider has not been added yet, you can call Security.getProvider()

to check it out. If the provider is not in the JVM, it returns null

:

// add provider only if it not in the JVM
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleProvider());
}

      

+5


source







All Articles