Adding Functionality to Existing Thread safe Classes

要实现一个增强版的线程安全类,有很多方法,但是目前我所知道最好的是使用组合方法。

比如要在线程安全的List中增加put-if-absent功能,可以这样:

@ThreadSafe
public class ImprovedList<T> implements List<T> {
private final List<T> list;
public ImprovedList(List<T> list) { this.list = list; }
public synchronized boolean putIfAbsent(T x) {
boolean contains = list.contains(x);
if (contains)
list.add(x);
return !contains;
}
public synchronized void clear() { list.clear(); }
// ... similarly delegate other List methods
}

  Java类库中的Collections.synchronizedXxx也是这样做的,看来这种方法不错。

当然还有别的方法:

使用继承

1 @ThreadSafe
2 public class BetterVector<E> extends Vector<E> {
3 public synchronized boolean putIfAbsent(E x) {
4 boolean absent = !contains(x);
5 if (absent)
6 add(x);
7 return absent;
8 }
9 }

  使用客户端锁机制

 1 @ThreadSafe
2 public class ListHelper<E> {
3 public List<E> list =
4 Collections.synchronizedList(new ArrayList<E>());
5 ...
6 public boolean putIfAbsent(E x) {
7 synchronized (list) {
8 boolean absent = !list.contains(x);
9 if (absent)
10 list.add(x);
11 return absent;
12 }
13 }
14 }

  但是好像都不是很好,详细参见《Java concurrency in practice》

当然,应该说没有最好吧,只有最适合才正确。因为组合方法要实现内部集合的所有操作,而这些是乏味、无趣的,客户端锁机制的话则只需实现想添加的操作就可以了。

原文地址:https://www.cnblogs.com/freewater/p/2139669.html