Question

In a scenario where server gives a client an unmodifiableCollection of an existing Collection, and client starts iterating over it, at the same time if at server level one thread changes the List, for example removes an element of it. Will this cause an exception to client? If yes then what it will be? Isn't it will be weird for the client when all of sudden it gets an exception while iterating the list?

Was it helpful?

Solution

First of all, it probably depends on a collection, since it is not specified anywhere inside Collection or Collections class.

Secondly, it is very simple to test it.

public class CollectionModTest {

    public static void main(String[] args) {
        Collection<String> original = new HashSet<String>();
        original.add("1");
        original.add("2");
        original.add("3");
        original.add("4");
        int counter= 5;

        Collection<String> unmodifiable = Collections.unmodifiableCollection(original);

        for (String val: unmodifiable) {
            System.out.println(val);
            original.add(""+counter);
            counter++;
        }

    }

}

Just replace the Collection implementations with implementations you use, and be certain if it'll throw an exception or not.

A good practice IMO would be to lose the original collection reference once you create an unmodifiable view of it. That way you will never have to worry about modifying the collection concurrently, because you will never be able to do it. Alternatively, if you have to modify the original collection soon after that, you can simply create a copy of the collection and iterate over it. The original collection can then be modified anywhere concurrently. The critical section will be as short as the new(copy) collection creation.

OTHER TIPS

Client can't change unmodifiableCollection, So remove is not allowed at unmodifiableCollection.

First it depends on what client is. If client receives the collection via network or some other means, then the changes on the server side collection don't change client's collection, since it's a different object on a different JVM.

If both server and client are refering to the same object inside same JVM, then it depends on how the client iterates.

If client does this: for(int i = 0;i < col.size();i++) { col.get(i);} then it will cause no error.

If client uses for(Object o : col) or if the client uses Iterator directly then you'll get a ConcurrentModificationException most of the time, on best effort basis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top