Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to make an ArrayList of ArrayLists thread safe. I also cannot have the client making changes to the collection. Will the unmodifiable wrapper make it thread safe or do I need two wrappers on the collection?

like image 558
WolfmanDragon Avatar asked Sep 17 '08 21:09

WolfmanDragon


People also ask

How can we make collections thread-safe in Java?

This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set. This method accepts an object of the Map interface and, returns a synchronized (thread-safe) sorted map backed by the specified sorted map.

Are collections thread-safe Java?

All collection classes (except Vector and Hashtable) in the java. util package are not thread-safe. The only two legacy collections are thread-safe: Vector and Hashtable.

What is Unmodifiable collection in Java?

The unmodifiableCollection() method of java. util. Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections.

Which collection implementation is thread-safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.


1 Answers

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.

like image 189
Michael Borgwardt Avatar answered Sep 21 '22 12:09

Michael Borgwardt