Adding Functionality to Existing Thread safe Classes
2011-08-15 17:13
92 查看
要实现一个增强版的线程安全类,有很多方法,但是目前我所知道最好的是使用组合方法。
比如要在线程安全的List中增加put-if-absent功能,可以这样:
Java类库中的Collections.synchronizedXxx也是这样做的,看来这种方法不错。
当然还有别的方法:
使用继承
使用客户端锁机制
但是好像都不是很好,详细参见《Java concurrency in practice》
当然,应该说没有最好吧,只有最适合才正确。因为组合方法要实现内部集合的所有操作,而这些是乏味、无趣的,客户端锁机制的话则只需实现想添加的操作就可以了。
比如要在线程安全的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也是这样做的,看来这种方法不错。
当然还有别的方法:
使用继承
@ThreadSafe public class BetterVector<E> extends Vector<E> { public synchronized boolean putIfAbsent(E x) { boolean absent = !contains(x); if (absent) add(x); return absent; } }
使用客户端锁机制
@ThreadSafe 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; } } }
但是好像都不是很好,详细参见《Java concurrency in practice》
当然,应该说没有最好吧,只有最适合才正确。因为组合方法要实现内部集合的所有操作,而这些是乏味、无趣的,客户端锁机制的话则只需实现想添加的操作就可以了。
相关文章推荐
- 添加react到已存在的项目中(Adding React to an Existing Application)-1
- Hibernate 中session.evict(obj):possible nonthreadsafe access to session
- Must Spring MVC Classes be Thread-Safe
- adding validation annotators to model classes 在linq to EntityFrame的Model中添加前台验证validation annotators
- How to: Make Thread-Safe Calls to Windows Forms Controls
- Adding React to an Existing Application
- Gradle Goodness: Init Script for Adding Extra Plugins to Existing Projects
- How to Keep Thread-Safe When Queuing Your Data
- How to: Make Thread-Safe Calls to Windows Forms Controls
- How to: Make Thread-Safe Calls to Windows Forms Controls
- QT QPixmap:It is not safe to use Pixmaps outside the GUI thread
- (VS TFS) Adding existing project to solution in TFS.
- Make ObservableCollection to thread safe (Updated)
- Spring Data JPA教程, 第八部分:Adding Functionality to a Repository (未翻译)
- QPixmap: It is not safe to use pixmaps outside the GUI thread原因
- Spring Data JPA教程, 第八部分:Adding Functionality to a Repository (未翻译)
- Adding a New Disk to an Existing Windows 2008 Cluster
- Categories Add Methods to Existing Classes
- Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
- How to: Make Thread-Safe Calls to Windows Forms Controls