The function we hope to achieve is to provide an atomic operation for List
: if not, add it. Because ArrayList
itself is not thread-safe, it is converted into a thread-safe class through the collection Collections.synchronizedList
, and then through an auxiliary method to List
Achieve such a function.
class BadListHelper <E> {
public List<E> list = Collections.synchronizedList(new ArrayList<E>());
public synchronized boolean putIfAbsent(E x) {
boolean absent = !list.contains(x);
if (absent)
list.add(x);
return absent;
}
}
Is this code thread-unsafe? If so, can you prove it? Thanks
漂亮男人2017-06-12 09:27:37
A non-repeating List is just a Set, right? , requires atoms, isn't it a thread-safe Set?