...
Prefer using the block form of synchronization when there are nonatomic operations within the method that do not require any synchronization. These operations can be decoupled from those that require synchronization and executed outside the synchronized block. You should also consider using an internal private lock object, as recommended by CON04-J. Synchronize using an internal private final lock object.
Noncompliant Code Example (synchronizedList)
...
This compliant solution uses a private object lock to synchronize the method bodies of the increment()
and getCount
methods, to ensure atomicity. For more information on private object locks, see CON04-J. Synchronize using an internal private final lock object.
Code Block | ||
---|---|---|
| ||
public class KeyedCounter { private final Map<String,Integer> map = new HashMap<String,Integer>(); private final Object lock = new Object(); public void increment(String key) { synchronized (lock) { Integer old = map.get(key); int value = (old == null) ? 1 : old.intValue() + 1; map.put(key, value); } } public Integer getCount(String key) { synchronized (lock) { return map.get(key); } } } |
...