Gregg Wonderly wrote:
...
A second issue is that if you are designing a "container" class that others might use in multiplicity such that it could end up in a container, and perhaps as a key data structure, it can be better to create an internal locking object to perform synchronization on so that if the user of your class starts using your class as a locking object, the internal locking does not impact unrelated code paths.
...

For container objects, I would give the opposite advice, and recommend making the container itself the lock object.

The reason is code that performs multiple operations on the container to do one related logical operation.

For example, I've been looking at some test code that needs to remove a random element from a List. It first uses a random number generator to pick an int n in the range 0 <= n < list.size(), followed by list.remove(n).

If done using a list that synchronizes on itself, that block of code can be marked synchronized(list), but code that does a single operation on list does not need to be synchronized externally. If the list synchronizes on an internal locking object, *all* access to the list will need to be synchronized in the calling code on some other object.

Using the container itself is also consistent with what is done by Collections.synchronizedList etc.

Patricia

Reply via email to