Does the unmodifiable wrapper for java collections make them thread safe? Does the unmodifiable wrapper for java collections make them thread safe? multithreading multithreading

Does the unmodifiable wrapper for java collections make them thread safe?


It depends. The wrapper will only prevent changes to the collection it wraps, not to the objects in the collection. If you have an ArrayList of ArrayLists, the global List as well as each of its element Lists need to be wrapped separately, and you may also have to do something for the contents of those lists. Finally, you have to make sure that the original list objects are not changed, since the wrapper only prevents changes through the wrapper reference, not to the original object.

You do NOT need the synchronized wrapper in this case.


On a related topic - I've seen several replies suggesting using synchronized collection in order to achieve thread safety.Using synchronized version of a collection doesn't make it "thread safe" - although each operation (insert, count etc.) is protected by mutex when combining two operations there is no guarantee that they would execute atomically.For example the following code is not thread safe (even with a synchronized queue):

if(queue.Count > 0){   queue.Add(...);}


The unmodifiable wrapper only prevents changes to the structure of the list that it applies to. If this list contains other lists and you have threads trying to modify these nested lists, then you are not protected against concurrent modification risks.