Reputation: 1307
We can use the Collections.synchronizedCollection(Collection c) for all objects of type Collection like Set and List right, why we have separate methods like - Collections.synchronizedList or Collections.synchronizedSet.
Upvotes: 0
Views: 834
Reputation: 1307
Yes it throws ClassCastException, i looked into the source code of the Collections class, the method Collections.synchronizedCollection(c) returns the wrapper synchronized methods only for Collection type, Where as the Collections.synchronizedList(list) method has the wrapper synchronized methods for all methods of the List, similarly for the Set also.
So have to use the specific synchronized methods in Collections for specific input type.
thanks for help.
Upvotes: 0
Reputation: 85779
There are other interfaces that are Collection
apart from List
and Set
e.g. Deque
. You could synchronize it using Collections#synchronizedCollection
.
Anyway, if you happen to work with synchronized collections, give a look at the classes at java.util.concurrent
package. Some of them are CopyOnWriteArrayList
(for List
) and CopyOnWriteArraySet
(for Set
).
Upvotes: 1
Reputation: 198033
If you call Collections.synchronizedCollection
on a List
, then you can't use the List
methods on the returned Collection
. In the other direction, you can't call Collections.synchronizedList
on something that might be an arbitrary Collection
, including a Set
.
Upvotes: 1