Thursday, March 31, 2011

Getting Synchronized set

By default set is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method like below :

Hashset :

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

TreeSet :

TreeSet
treeSet = new TreeSet(); 
Set set = Collections.synchronizedSet(treeSet);

No comments:

Post a Comment

Chitika