I\'ve read around quite a bit but haven\'t found a definitive answer.
I have a class that looks like this:
public class Foo() {
private
Initialization of static final fields in a static initialization block is thread safe. However, remember that the object to which a static final reference points may not be thread safe. If the object to which you refer is thread safe (e.g., it's immutable), you're in the clear.
Each individual HashMap contained in your outer HashMap is not guaranteed to be thread safe unless you use ConcurrentHashMap as suggested in your question. If you do not use a thread-safe inner HashMap implementation, you may get unintended results when two threads access the same inner HashMap. Keep in mind that only some operations on ConcurrentHashMap are synchronized. For example, iteration is not thread-safe.
the reference to sharedData
which is final is thread safe since it can never be changed. The contents of the Map is NOT thread safe because it needs to be either wrapped with preferably a Guava ImmutableMap
implementation or java.util.Collections.unmodifiableMap()
or use one of the Map implementations in the java.util.concurrent
package.
Only if you do BOTH will you have comprehensive thread safety on the Map. Any contained Maps need to be immutable or one of the concurrent implementations as well.
cloning by default is a shallow clone, it will just return references to container objects not complete copies. It is well documented in generally available information on why.