recently read "Java concurrent programming practice," in Section 4.4.1, there is an example: suppose we need a thread-safe List, that needs to provide us with an atomic "put-if-absent" operation. And two implementations are provided:
- A non-thread-safe add-as-you-go implementation
public class ListHelper<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;
}
}
- add what you want using client-side locking
public class ListHelper<E> {
public List<E> list = Collections.synchronizedList(new ArrayList<E>());
public boolean putIfAbsent(E x) {
synchronized (list) {
boolean absent = !list.contains(x);
if (absent) {
list.add(x);
}
return absent;
}
}
}
I feel that the translation in the book is rather obscure. I have never understood why the first one is non-thread-safe and the second is thread-safe. Please take a look at what"s going on
.