Why do synchronized wrappers exist for List,Set,Map when there is Collections.synchronizedCollection()

259 Views Asked by At

Does anyone know why should I (for example) put my List inside Collections.syncrhonizedList() instead of Collections.synchronizedCollection()? Do they work the same? Same applies to Map,Set.

Another thing. Why there isn't Collections.synchronizedQueue()?

1

There are 1 best solutions below

2
On

When you are using synchronizedCollection() to synchronize an ArrayList, the list-specific methods are not synchronized, so the more concrete method, the better. Beware that method Collections.synchronizedList() will synchronize all the accesses to the backed list except while iterating which still needs to be done within a synchronized block with the synchronized List instance as object's monitor. One more thing, when you create synchronized collection using Collections.synchronizedCollection like this :

Collection c = Collections.synchronizedCollection(yourCollection);

Then, according to documentation, the returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.