A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. In the absence of such a policy, it is possible to introduce a data race condition. If two or more operations need to be performed as a single atomic operation, it is necessary to implement a consistent locking policy by either using intrinsic synchronization or the java.util.concurrent
utilities.
Given an invariant involving multiple objects, a programmer may incorrectly assume that individually atomic operations require no additional locking; however, this is not the case. Similarly, programmers sometimes may incorrectly assume that using a thread-safe Collection
does not require explicit synchronization to preserve an invariant that involves the collection's elements. A thread-safe class can only guarantee atomicity of its individual methods. A grouping of calls to such methods requires additional synchronization.
For Consider, for example, consider a scenario where the standard thread-safe API does not provide a method to both find a particular person's record in a Hashtable
and also update the corresponding payroll information. In such cases, a custom atomic method must be designed and used. This guideline discusses the rationale behind using such a method and provides the relevant implementation advice.
Enumerations and iterators of objects of a Collection
also require explicit synchronization on the Collection
object (client-side locking) or an internal private lock object.
Expressions involving compound operators Compound operations on shared variables are also non-atomic. Refer to See CON01-J. Ensure that compound operations on shared variables are atomic for more information.
...