Wiki Markup |
---|
Synchronizing a class is |
unnecessary when |
it is designed for single-threaded use. Such classes are required to document |
their lack of thread-safety. For instance, the documentation of class {{java.lang.StringBuilder}} states \[[API 06|AA. Java References#API 06]\] : |
This class is designed for use as a drop-in replacement for
StringBuffer
in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference toStringBuffer
as it will be faster under most implementations.
Any multithreaded client must externally synchronize operations on an object that is Multithreaded clients of classes that are not thread-safe must externally synchronize any accesses if the documentation of the corresponding class states that it is not thread-safe.the classes specify the lack of thread-safety, or fail to provide any conclusive information.
Classes However, classes that use mutable static
fields must always internally synchronize accesses to their fields. This is because there is no guarantee that all clients will synchronize externally when accessing the field. Because a static
field is shared by all clients, unrelated clients may violate the contract by not performing adequate synchronization.
...
It relies on clients to externally synchronize the object and states specifies its unsafe behavior in the documentation. However, there is no guarantee that all unrelated (trusted or untrusted) clients will follow this advice.
...
This compliant solution internally synchronizes the counter
field and consequently, does not depend on any external synchronization.
...