Ease of use of synchronized ... methods in java.util.Collections

I am looking at a static method

Collections.synchronizedList(List<T> list)

Javadok says

It is imperative that the user manually synchronizes in the returned list when repeating on it ...

What is the purpose of creating a synchronized list if I still need to manually synchronize it?

+3
source share
2 answers

Reason for use

Collections.synchronizedList(List<T> list)  

lies in the fact that all methods except the iterator are synchronized using the list itself as a mutex, so you do not need to do

synchronized(list) {
    list.add(type);
}   

Instead, you can simply do

list.add(type);  

and it will be thread safe.

, , - . , , . , , , .

+7

java . , . .

+1

Source: https://habr.com/ru/post/1728876/


All Articles