Is Cipher thread-safe? Is Cipher thread-safe? java java

Is Cipher thread-safe?


No, it isn't. The instance is stateful. So you need to store it threadlocal, or to obtain a new instance on every encrypt/decrypt call, or to wrap it in a synchronized(cipher) block.

Threadsafety is usually mentioned in javadocs as "is thread safe" or "is not thread safe". This is not the case for Cipher, so you should not assume it to be threadsafe.


Even if a Cipher was thread-safe, it would not really be useful to use it from multiple threads concurrently.

The bytes you put into and get out of the Cipher (via its update and finish methods) are a continuous stream. This means, on the other end, they have to be passed in the same order to make any sense. This is easiest to accomplish if you have only one thread doing this.

If you are using multiple threads, you usually would want to call reset between the calls - and then you will need external synchronization anyways.


I wouldn't use Cipher objects from multiple threads without synchronization. When you look at the API, there are methods which can only work by changing internal state, such as init() and update(). That makes them implicitly non-thread-safe.