Are the verify methods in java.security.cert.Certificate thread-safe?
In general, can the verify-methods in java.security.cert.Certificate be considered thread-safe? Specifically, verify(PublicKey key) and verify(PublicKey key, String sigProvider). Can multiple threads call these methods simultaneously without worrying that they will modify internal data in a thread-unsafe way?
The JavaDoc 开发者_Python百科does not mention anything about this. Perhaps this is implementation specific?
I would like to do something like this:
Certificate certificate = getCertificateFromCache();
certificate.verify(whatever);
Ideally without putting it in a synchronized block.
Certificate.verify
is an abstract method. So from this perspective there can't be any guarantee, that all implementations are always thread-safe. Maybe the documentation of the actual certificate implementation tells you something about it, but, to be safe, you may have to synchronize the call to verify on the actual certificate.
Maybe you can create something like a pool of equal certificate instances to bypass that problem. Then you could verify in parallel on different instances of the same certificate.
Looking at sun.security.x509.X509CertImpl
source, it has some synchronized
methods (including verify
) and a private ConcurrentHashMap<String,String> fingerprints
field.
So it seems to me that there was a clear intent to make it thread-safe.
Unfortunately synchronized
methods updating inner state fields like verificationResult
, verifiedPublicKey
, verifiedProvider
would incur some performance overhead during concurrent access from many threads.
It may be more efficient to avoid synchronized
locks contention by caching instances in ThreadLocal
, for example.
精彩评论