Is KeyFactory thread safe?

There is a service class that should generate instances PublicKeyfrom X.509 public key representations. One instance of this class will serve multiple threads. Is it right to do something like this?

public class MyService {
    private final KeyFactory rsaKeyFactory;

    public MyService() throws NoSuchAlgorithmException {
        rsaKeyFactory = KeyFactory.getInstance("RSA");
    }

    public PublicKey generatePublicKey(byte[] publicKeyBytes) throws GeneralSecurityException {
        return rsaKeyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
    }
}

those. is the instance KeyFactoryused here thread safe? generatePublicKey()a method can be called by different threads at the same time.

Javadocs does not seem to mention thread safety.

+4
source share
2 answers

, Javadoc , ( " - " ). [1] synchronized generatePublicKey ( - ) Javadoc, , .

. :

  • , Javadoc, , ?
  • ()

    Javadoc : " ?" . , , -, ( !), , , , , , ( ). , , , .

    [...]

    . (), . , . , , Javadoc.


....

, ( , , , KeyFactory, KeyFactory#generatePublic ).

-, KeyFactory.getInstance(String) : [2] [3]

public static KeyFactory getInstance(String algorithm)
        throws NoSuchAlgorithmException {
    return new KeyFactory(algorithm);
}

:

private KeyFactory(String algorithm) throws NoSuchAlgorithmException {
    this.algorithm = algorithm;
    List<Service> list = GetInstance.getServices("KeyFactory", algorithm);
    serviceIterator = list.iterator();
    // fetch and instantiate initial spi
    if (nextSpi(null) == null) {
        throw new NoSuchAlgorithmException
            (algorithm + " KeyFactory not available");
    }
}

nextSpi :

private KeyFactorySpi nextSpi(KeyFactorySpi oldSpi) {
    synchronized (lock) {
        // Truncated for brevity
    }
}

KeyFactory#generatePublic :

public final PublicKey generatePublic(KeySpec keySpec)
        throws InvalidKeySpecException {
    if (serviceIterator == null) {
        return spi.engineGeneratePublic(keySpec);
    }
    // Truncated for brevity
}

, , , ( , ) , thread-saftey. , , factory , . .

, , , , , , Javadoc.

+3

, , , .

0

Source: https://habr.com/ru/post/1676246/


All Articles