What is purpose of Collections.unmodifiableCollection

Carvia Tech | October 03, 2020 | 1 min read | 20 views | Multithreading and Concurrency

What does Collections.unmodifiableCollection() do? Is it safe to use the collection returned by this method in a multi-threading environment?

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() {
        Collection < String > dynamicView = Collections.unmodifiableCollection(names);
        for (String s: dynamicView) {   (1)
            System.out.println("s = " + s);
            names.remove(0); (2)
    public static void main(String[] args) {
        UnModifiableCollection test = new UnModifiableCollection();
1 this will throw ConcurrentModification in 2nd iteration
2 this is the culprit line modifying the underlying collection

Hence, external synchronization is must if we are going to modify the underlying collection, even if you are using Collections.unmodifiableCollection().

Top articles in this category:
  1. What are four principles of OOP, How aggregation is different than Composition?
  2. Is Java Pure Object Oriented Language?
  3. What is difference between sleep() and wait() method in Java?
  4. What is difference between ExecutorService submit and execute method
  5. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  6. What is difference between HashMap and HashSet
  7. What is Double Checked Locking Problem in Multi-Threading?

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info