Rule 5:Document thread safety
If You fail to document – how a method behaves when it is called concurrently, It’s user will be forced to make
assumptions. it may result in serious error, if assumptions are wrong ,where in putting less synchronization or
excessive synchronization.
YOU MAY HEAR IT SAID that you can tell if a method is thread-safe or not by looking for synchronized modifier in it’s documentation. This is wrong on several counts,Javadoc doesnot include synchronized in it’s output.
The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its API. It does not reliably indicate that a method is thread-safe.
Morever, the claim that the presence of the synchronized modifier is sufficient
to document thread safety embodies the misconception that thread safety is
an ALL-OR-NOTHING PROPERTY .
however to enable safe concurrent use, following are the levels of thread safety that it must document to support.
Note on Mutable and immutability: if object is immutable no need to worry of being changed by another thread.
if mutable means probably it has (two or more) different state bcoz of concurrent use there is need to maintain single state – by synchrnination (or by making it final).
1.Immutable :
Instances of this class appear constant. No external synchronization is necessary.
Examples include String, Long, and BigInteger.
2.Unconditional Thread Safe :
Instances of this class are mutable But sufficient internal synchoronisation no need of external synchoronisation
Example:
AtomicLong and ConcurrentHashMap.
3.Conditional Thread Safe :
Like unconditionally thread-safe, except that some methods require external synchronization for safe concurrent use.
Examples include the collections returned by the Collections.synchronized wrappers, whose iterators require external synchronization
4.Not thread safe : Instances of this class are mutable.To use them concurrently,
clients must surround each method invocation (or invocation sequence) with external synchronization.
Example : ArrayList and HashMap.
5.Thread hostile :
This class is unsafe for concurrent use even if every method invocation is surrounded by external synchronization .Thread hostility usually results from modifying static data without synchronization.
If you write an UNCONDITIONALY THREAD-SAFE CLASS, consider using a PRIVATE LOCK OBJECT in
place of synchronized methods. This protects you against synchronization
interference by clients and subclasses and gives you more flexibility to adopt a
sophisticated approach to concurrency control in a later release.
CONDITIONALLY THREAD SAFE CLASSES can’t use this idiom because they must
document which lock their clients are to acquire when performing certain method
invocation sequences.