Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is CertificateFactory.getInstance("x.509") thread safe?

I'm not able to find out whether CertificateFactory.getInstance("x.509") is thread safe or not? Can someone please clarify?

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

Thanks in advance.

like image 598
thirstylad Avatar asked May 05 '17 16:05

thirstylad


1 Answers

This question is old but it's the first google hit for the question, so here goes:

The result of your call is a CertificateFactory implementation, specifically (in Oracle Java) a sun.security.provider.X509Factory. That factory only has static instance members which [I checked 'em] are threadsafe. It also has a number of synchronized static methods, which indicate that the class was built with thread safety in mind.

So I'd say that in practice, if you're assured that you're using Oracle Java(tm) then you can assume thread safety; however, you'll need to check other JREs if you're using them. You could always just be safe and wrap the value in ThreadLocal, eg:

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);
    }
}
like image 150
Daryl Banttari Avatar answered Sep 25 '22 04:09

Daryl Banttari