The Random class does not offer any guarantees about whether a Random object is thread-safe or not; therefore, we must assume it's not inherently therad-safe, and if we require thread safety, we must ensure it ourselves. (Usually through synchronization.) This is true of just about all classes in
Java: if you can't find documentation assuring thread safety, assume it's not thread-safe. Note that Math.random()
does guarantee it's safe for use by multiple threads (because the Math class provides the necessary synchronization). But the Random class does not.
Arun's code will probalby work, though it's not immediately clear to look at it - we don't know how the Random instance relates to the WeakHashMap. Is it a one-to-one relationship? (Probably.) But it seems more straightforward to sync on the Random instance instead. This makes sense, as it's the thread safety of the Random instance that concerns us. Why sync on something else?