Sonarqube - performance issue as Method uses a FileInputStream constructor, what are the better alternatives?

Viewed 506

Here is my code :

        KeyStore truststore = KeyStore.getInstance("JKS");
        truststore.load(new FileInputStream(TRUSTSTORE_FILE), 
                                           TRUSTSTORE_PASSWORD.toCharArray()); //sonarqube issue

Which is the most suitable InputStream for getting this done?

Here is the full error :

This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method, which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected.

Do I really need to switch to :

InputStream is = java.nio.file.Files.newInputStream(myfile.toPath());

I am not comfortable with this one.

1 Answers

Wrap it in a try-with-resources so it will be closed at the end of the block. The error message is complaining that the file might be open a long time.

try (InputStream in = new FileInputStream(TRUSTSTORE_FILE)) {
    KeyStore truststore = KeyStore.getInstance("JKS");
    truststore.load(in, TRUSTSTORE_PASSWORD.toCharArray());
} // Automatically closes in.

This frees system resources (a file handle) and allows others to overwrite the truststore file.

Related