The current implementation of SecureRandom is thread safe, in particular, the two mutating methods nextBytes(bytes[]) and setSeed(byte[]) synchronized.
Well, as far as I could tell, all mutating methods end up being routed through these two methods, and SecureRandom overrides several methods in Random to guarantee this. This works, but can be fragile if the implementation is changed in the future.
The best solution is to manually sync first in the SecureRandom instance. This means that each call stack will acquire two locks on the same object, but usually it is very cheap on modern JVMs. That is, there is no harm in explicit synchronization. For example:
SecureRandom rnd = ...; byte[] b = new byte[NRANDOM_BYTES]; synchronized (rnd) { rnd.nextBytes(b); }
Matt Quail Apr 28 '10 at 4:47 april 2010-04-28 04:47
source share