Is the CertificateFactory.getInstance ("x.509") file safe?

I can't find out if CertificateFactory.getInstance ("x.509") is thread safe or not? Can someone clarify?

https://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html

Thanks in advance.

+5
source share
1 answer

This question is old, but this is the first google hit for the question, so here goes:

The result of your call is the implementation of CertificateFactory , in particular (in Oracle Java) sun.security.provider.X509Factory . This factory has only static instance members that [I tested them] are thread safe. It also has several synchronized static methods that show that the class was built with thread safety in mind.

So, I would say that in practice, if you are sure that you are using Oracle Java (tm), you can assume thread safety; however, you will need to check out other JREs if you use them. You can always be safe and wrap the value in ThreadLocal , for example:

 private static final ThreadLocal<CertificateFactory> certFactory = ThreadLocal.withInitial(() -> { try { return CertificateFactory.getInstance("x.509"); } catch (Exception e) { throw new RuntimeException(e); } }); 

and then later

 public Certificate loadCertFrom(String filename) throws IOException, CertificateException { try (final FileInputStream in = new FileInputStream(filename)) { return certFactory.get().generateCertificate(in); } } 
0
source

All Articles