package net.jcip.examples;
import java.util.*;
import net.jcip.annotations.*;
/**
* ListHelder
*
* Examples of thread-safe and non-thread-safe implementations of
* put-if-absent helper methods for List
*
* @author Brian Goetz and Tim Peierls
*/
@NotThreadSafe
class BadListHelper {
public List list = Collections.synchronizedList(new ArrayList());
public synchronized boolean putIfAbsent(E x) {
boolean absent = !list.contains(x);
if (absent)
list.add(x);
return absent;
}
}
@ThreadSafe
class GoodListHelper {
public List list = Collections.synchronizedList(new ArrayList());
public boolean putIfAbsent(E x) {
synchronized (list) {
boolean absent = !list.contains(x);
if (absent)
list.add(x);
return absent;
}
}
}