Collections.unmodifiableCollection() returns a unmodifiable dynamic view of underlying data structure. Any attempt direct or via iterator to modify this view throws UnsupportedOperationException, but any changes made in the underlying data structure will be reflected in the view.
This method is no substitute for the other thread safety techniques because iterating over a collection using this view may throw ConcurrentModificationException if original collection is structurally modified during the iteration.
For example, the following code will throw ConcurrentModificationException in the for loop.
public class UnModifiableCollection {
private List < String > names = new ArrayList < > ();
public void testConcurrency() {
names.add("1");
names.add("2");
names.add("3");
names.add("4");
Collection < String > dynamicView = Collections.unmodifiableCollection(names);
for (String s: dynamicView) { <= == will
throw ConcurrentModification in 2nd iteration
System.out.println("s = " + s);
names.remove(0); <= == The culprit line modifying the underlying collection
}
}
public static void main(String[] args) {
UnModifiableCollection test = new UnModifiableCollection();
test.testConcurrency();
}
}
Hence, external synchronization is must if we are going to modify the underlying collection.
This method is no substitute for the other thread safety techniques because iterating over a collection using this view may throw ConcurrentModificationException if original collection is structurally modified during the iteration.
For example, the following code will throw ConcurrentModificationException in the for loop.
public class UnModifiableCollection {
private List < String > names = new ArrayList < > ();
public void testConcurrency() {
names.add("1");
names.add("2");
names.add("3");
names.add("4");
Collection < String > dynamicView = Collections.unmodifiableCollection(names);
for (String s: dynamicView) { <= == will
throw ConcurrentModification in 2nd iteration
System.out.println("s = " + s);
names.remove(0); <= == The culprit line modifying the underlying collection
}
}
public static void main(String[] args) {
UnModifiableCollection test = new UnModifiableCollection();
test.testConcurrency();
}
}
Hence, external synchronization is must if we are going to modify the underlying collection.
No comments:
Post a Comment
Your comment will be published after review from moderator