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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With