首页 > 编程语言 > 详细

设计线程安全的类

时间:2014-09-20 19:32:50      阅读:307      评论:0      收藏:0      [点我收藏+]

步骤:

找出构成对象状态的所有变量

找出约束状态变量的不变性条件

建立对象状态的并发访问策略

 

1.在现有的线程安全类中添加功能

(1)重用能减低工作量和提高正确性

(2)如果底层的类改变了同步策略,使用不同的锁来保护它的状态,则子类会被破坏

class BetterVector<E> extends Vector<E>{
    public  synchronized boolean putIfAbsent(E e){
        boolean absent = !contains(e);
        if(absent){
            add(e);
        }
        return absent;
    }
}

 

2.客户端加锁机制

(1)对于使用对象X的客户端,如果知道X使用的是什么锁,则使用X本身用于保护其状态的锁,来保护这段客户端代码

(2)同样会破坏同步策略的封装

  A.错误示例:

class ListHelper<E>{
    public List<E> list = Collections.synchronizedList(new ArrayList<E>());
    
    public synchronized boolean putIfAbsent(E e){
        boolean absent = !list.contains(e);
        if(absent){
            list.add(e);
        }
        return absent;
    }
}

 B.正确示例:

class ListHelper<E>{
    public List<E> list = Collections.synchronizedList(new ArrayList<E>());
    
    public  boolean putIfAbsent(E e){
        synchronized(list){
            boolean absent = !list.contains(e);
            if(absent){
                list.add(e);
            }
            return absent;
        }
    }
}

 

3.组合:推荐方式

class ImprovedList<E> implements List<E>{
private final List<E> list;
public ImprovedList(List<E> list){ this.list = list; } public synchronized boolean putIfAbsent(E e){ boolean absent = !list.contains(e); if(absent){ list.add(e); } return absent; } public synchronized boolean add(E e) { //委托..... } }

 

设计线程安全的类

原文:http://www.cnblogs.com/yuyutianxia/p/3983562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!