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
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
A non-repeating List is just a Set, right? , requires atoms, isn't it a thread-safe Set?