Like what others have mentioned, synchronized collections are thread-safe , but composite actions for these collections do not guarantee streams by default.
According to JCIP, common connection actions can be
- iteration
- navigation
- put-if-missing
- check act
The synchronized OP code block is not a composite action, so it makes no difference whether you add it or not.
Take an example from JCIP and modify it a bit to find out why it is necessary to protect compound actions with blocking.
There are two methods that work in the same list collection wrapped in Collections.synchronizedList
public Object getLast(List<String> list){ int lastIndex = list.size() - 1; return list.get(lastIndex); } public void deleteLast(List<String> list){ int lastIndex = list.size() - 1; list.remove(lastIndex); }
If the getLast and deleteLast are called simultaneously by two different threads, alternations can occur below, and getLast will throw an ArrayIndexOutOfBoundsException . Suppose the current lastIndex is 10.
Subject A (deleteLast) -> delete
Theme B (getLast) --------------------> get
Thread A remove element before the get operation in thread B. Thus, thread B still uses 10 as the lastIndex method to call the list.get method, this will lead to a simultaneous problem.
Gearon Nov 20 '17 at 13:42 on 2017-11-20 13:42
source share