Initialising SSLContext in case of multiple threads

Viewed 132

I am trying to initialise a SSLContext with a custom truststore and keeping keystore and secureRandom as default. For the custom truststore I have a JKS file which I will use to initialise TrustManagers. This is a server application which will get multiple concurrent requests. I am not able to understand if we should use a singleton SSLContext/SSLSocketFactory or not. Based on Are SSLContext and SSLSocketFactory createSocket thread safe?, it looks like we should create new objects for every request. But then, the below implementation will cause high latency for loading truststore and creating SSL object for every request. Is this understanding correct?

Also, it will be very helpful if I could understand how to check if a particular object can be singleton in such cases? In the documentation I generally look for mention about being thread safe, but I could not find any such information in oracle documentation for SSLContext/SSLSocketFactory.

URL url = new URL(endpoint);
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(getDefaultSSLSocketFactory());

public SSLSocketFactory getDefaultSSLSocketFactory() {
        String path = "path to truststore";
        try (FileInputStream fis = new FileInputStream(path)) {
            SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
            KeyStore clientKeyStore = KeyStore.getInstance("JKS");
            clientKeyStore.load(fis, "password".toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(clientKeyStore);
            sslcontext.init(null, trustManagerFactory.getTrustManagers(), null);
            return sslcontext.getSocketFactory();
}
0 Answers
Related