Adding Security Provider multiple times in Java application

Aman :

We have a Java application where a job is scheduled to run every 5 minutes. In that job, there is a security component that does the following every time it is executed:

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

My questions are:

  1. Is it required to add the security provider multiple times in the application? Does it serve any purpose? To me, it doesn't make sense and adding it once should suffice.
  2. Is it a candidate for a potential memory leak in the application?

To clarify, I want to add Bouncy Castle security provider programmatically in my application and not statically via JRE. IMO, adding Bouncy Castle security provider once in the application is enough and I need not do in multiple times.

user7605325 :

According to addProvider's javadoc:

Returns:
the preference position in which the provider was added, or -1 if the provider was not added because it is already installed

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

Of course you can optimize it and put just a single call in a main class (some class that you know it's always loaded at application startup), but I wouldn't worry much about that.

I had worked with systems that had more than one call to addProvider in different parts (because they could be called in any order and were independent from each other), all running in the same JVM, and it never got any memory leaks. Of course it's just my case, but I'm not aware of this causing leaks.


If you want to call addProvider only if the provider is not added yet, you can call Security.getProvider() to check that. If the provider is not in the JVM, it returns null:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=445144&siteId=1