This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.
public static <T> Collection<T> synchronizedCollection(Collection<T> c);
public static <T> Set<T> synchronizedSet(Set<T> s);
public static <T> List<T> synchronizedList(List<T> list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);
Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.
I'm wondering here, if we've synchronizedMap() and synchronizedSet() methods then what were need of synchronizedSortedSet() and synchronizedSortedMap() methods seperately ?
Couldn't synchronizedSet() make thread-safe SortedSet ? Now what is need of synchronizedSortedSet() here ?
And what about if i want to make thread-safe HashSet ? I believe SynchronizedSet() will work with it, as it did above.
As you might already know SortedSet and SortedMap are Interfaces which extend the behaviour of their parent interfaces. Say you have a SortedSet variable an you need a syncronized one you could not do it without casting to SortedSet because synchronizedSet would return a normal Set. Those methods are mostly for the convenience.
In the face of concurrent access, it is imperative that the user manually synchronize on the returned collection when iterating over it. The reason is that iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation. The following is the idiom to iterate over a wrapper-synchronized collection.
Collection<Type> c = Collections.synchronizedCollection(myCollection);
for (Type e : c)
If an explicit iterator is used, the iterator method must be called from within the synchronized block. Failure to follow this advice may result in nondeterministic behavior.
Why should i call iterator() inside synchronization block ?, is it not synchronized ?,if my backed Collection is synchronized then it must be also synchronized ?