BZapper
BZapper

Reputation: 330

Create and maintain multiple Ciphers

I'm running into an issue where multiple threads are fighting over an RSA javax.crypto.Cipher, and I'm looking into keeping a collection of Ciphers - one for each thread. However Cipher.getInstance() gives me the same instance. Should I look into a clone() or is there a better way, like a new Cipher()? We've considered synchronized{} and just use single instance of Cipher but it's too slow. Thanks for all the help in advance!

Upvotes: 4

Views: 4498

Answers (1)

Gray
Gray

Reputation: 116888

It looks to me that different threads get different Cipher instances -- at least under JDK 1.6.0_33 under Mac OSX. Maybe this is because I'm using BouncyCastle provider?

Were you trying to call getInstance() from the same thread twice or from different threads? clone() does not seem to be available for Ciphers so that is not an option.

One solution would be to use object pools so that multiple cipher instances would be used in parallel by multiple threads. This might not work if the the JDK returns the same cipher instance on the same thread instead of a new instance.

The following code seems to spit out different identity hashcode objects for me at least:

private static final ThreadLocal<Cipher> localDigest = new ThreadLocal<Cipher>(){
    @Override
    protected Cipher initialValue() {
        try {
            return Cipher.getInstance("RSA");
        } catch (Exception e) {
            // ugly but necessary
            throw new RuntimeException(e);
        }
    }
};

public static void main(String[] args) {
    new Thread(new MyRunnable()).start();
    new Thread(new MyRunnable()).start();
}

private static class MyRunnable implements Runnable {
    @Override
    public void run() {
        Cipher cipher = localDigest.get();
        System.out.println("Got digest " + System.identityHashCode(cipher));
        ...
    }
}

As pointed out by @marius_neo in the comments, ThreadLocals can cause memory leaks in certain situations. See: To Pool or not to Pool java crypto service providers

Upvotes: 6

Related Questions