Thursday, 5 November 2015

Collection class: Thread-Safe Collections

Thread-Safe Collections :-  Similar to read-only collections, thread-safe collections are factory decorators that wrap instances of the six core interfaces into thread-safe versions.

  • Collection synchronizedCollection(Collection collection)
  • List synchronizedList(List list)
  • Map synchronizedMap(Map map)
  • Set synchronizedSet(Set set)
  • SortedMap synchronizedSortedMap(SortedMap map)
  • SortedSet synchronizedSortedSet(SortedSet set)

Synchronize the collection immediately after creating it. You also must not retain a reference to the original collection, or else you can access the collection unsynchronized. The simplest way to make sure you don't retain a reference is never to create one:

Set set = Collections.synchronizedSet(new HashSet());

Making a collection unmodifiable also makes a collection thread-safe, as the collection can't be modified. This avoids the synchronization overhead.

public static void main(String[] args) {  
           Set set = Collections.synchronizedSet(new HashSet());  
           synchronized (set) {  
                Iterator itr = set.iterator();  
                while (itr.hasNext()) {  

The iterator itself is not synchronized and iterating through a collection requires multiple calls back into the collection. If you don’t synchronize the getting and use of your iterator, your iteration through the collection will not be atomic and the underlying collection may change.

Enjoy Reading.

No comments:

Post a Comment