Thread safety of a class is not an all-or-nothing proposition and is difficult to define.
eg: The methods of
Vector
are all synchronized, and Vector
is clearly designed to function in multithreaded environments. But there are limitations to its thread safety, namely that there are state dependencies between certain pairs of methods. (Similarly, the iterators returned by Vector.iterator()
will throw a ConcurrentModificationException
if the Vector
is modified by another thread during iteration.)Joshua Bloch has suggested following five levels of thread safety of a class :
Immutable: Instances of the class are constant and cannot be changed. There are, therefore, no thread safety issues.
eg:Integer,String,and BigInteger
Thread-safe: Instances of the class are mutable but they can be used safely in a concurrent environment. All methods provided by the class are properly synchronized either at the interface level or internally within the method.
eg:Timer
Conditionally thread-safe: Instances of the class for which each individual operation may be thread-safe, but certain sequences of operations may require external synchronization.
eg:Hashtable and Vector
Explanation-Iterator returned by Vector class assumes that the underlying collection will not be mutated while the iterator traversal is in progress. To ensure that other threads will not mutate the collection during traversal, the iterating thread should be sure that it has exclusive access to the collection for the entirety of the traversal. Typically, exclusive access is ensured by synchronizing on a lock -- and the class's documentation should specify which lock that is (typically the object's intrinsic monitor)
Thread-compatible: Instances of the class provide no synchronization. However, instances of the class can be safely used in a concurrent environment, if the caller provides the synchronization by surrounding each method (or sequence of method calls) with the appropriate lock.
eg:ArrayList,HashMap,java.text.SimpleDateFormat
Thread-hostile: Instances of the class should not be used in a concurrent environment even if the caller provides external synchronization. Ideally, classes should not be written that are thread-hostile. Typically a thread-hostile class is accessing static data or the external environment.
eg:Class which calls System.setOut().
The developer for a java class should mention the thread safety in terms of one of the levels mentioned above in the Javadoc. This would help the people who would be maintaining the class in future and also the consumers of these classes.
2001), Effective Java: Programing Language Guide, Addison-Wesley.
(
No comments:
Post a Comment