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

前端 未结 9 687
小鲜肉
小鲜肉 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: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(...);
    }
    

提交回复
热议问题