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

前端 未结 9 689
小鲜肉
小鲜肉 2020-12-30 02:10

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 d

相关标签:
9条回答
  • 2020-12-30 02:30

    It will be thread-safe if the unmodifiable view is safely published, and the modifiable original is never ever modified (including all objects recursively contained in the collection!) after publication of the unmodifiable view.

    If you want to keep modifying the original, then you can either create a defensive copy of the object graph of your collection and return an unmodifiable view of that, or use an inherently thread-safe list to begin with, and return an unmodifiable view of that.

    You cannot return an unmodifiableList(synchonizedList(theList)) if you still intend to access theList unsynchronized afterwards; if mutable state is shared between multiple threads, then all threads must synchronize on the same locks when they access that state.

    0 讨论(0)
  • 2020-12-30 02:31

    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(...);
    }
    
    0 讨论(0)
  • 2020-12-30 02:34

    From looking at the Collections source, it looks like Unmodifiable does not make it synchronized.

    static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
                     implements Set<E>, Serializable;
    
    static class UnmodifiableCollection<E> implements Collection<E>, Serializable;
    

    the synchronized class wrappers have a mutex object in them to do the synchronized parts, so looks like you need to use both to get both. Or roll your own!

    0 讨论(0)
提交回复
热议问题