创建线程安全对象的几种方式

实例封闭

确保对象只能由单个线程访问(线程封闭),或者通过一个锁来保护对该对象的所有访问,以确保对象是线程安全的。

实例代码:

@ThreadSafe
public class PersonSet {
    @GuardedBy("this")
    private final Set<User> mySet = new HashSet<>();

    public synchronized void addUser(User user) {
        mySet.add(user);
    }

    public synchronized boolean containsUser(User user) {
        return mySet.contains(user);
    }
}

及通过“装饰器”封装容器类实现线程安全:

List list = Collections.synchronizedList(new ArrayList());
Map map = Collections.synchronizedMap(new HashMap());

线程安全性的委托

在某些情况下,通过多个线程安全类组合而成的类是线程安全的。

实例代码:

@ThreadSafe
public class DelegatingVehicleTracker {
    private final ConcurrentMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(Map<String, Point> points) {
        this.locations = new ConcurrentHashMap<String, Point>(points);
        this.unmodifiableMap = Collections.unmodifiableMap(locations);
    }
    
    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }
    
    public Point getLocation(String id) {
        return locations.get(id);
    }
    
    public void setLocation(String id, Point point) {
        if(locations.replace(id, point) == null) {
            throw new IllegalArgumentException("invalid vehicle name: " + id);
        }
    }
}
@ThreadSafe
public class VisualComponent {
    private final List<KeyListener> keyListeners = new CopyOnWriteArrayList<>();
    private final List<MouseListener> mouseListeners = new CopyOnWriteArrayList<>();

    public void addKeyListener(KeyListener keyListener) {
        keyListeners.add(keyListener);
    }

    public void removeKeyListener(KeyListener keyListener) {
        keyListeners.remove(keyListener);
    }

    public void addMouseListener(MouseListener mouseListener) {
        mouseListeners.add(mouseListener);
    }

    public void removeMouseListener(MouseListener mouseListener) {
        mouseListeners.remove(mouseListener);
    }
}

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

重用现有的类可以降低开发工作量、开发风险

实例代码:

/**
 * 扩展Vector
 *
 **/
@ThreadSafe
public class BetterVector<E> extends Vector<E> {
    public synchronized boolean putIfAbsent(E e) {
        boolean absent = contains(e);
        if (!absent) {
            add(e);
        }
        return absent;
    }
}
@ThreadSafe
public 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;
        }
    }
}

参考:《Java并发编程实战》

发布了11 篇原创文章 · 获赞 1 · 访问量 1638

猜你喜欢

转载自blog.csdn.net/u011578173/article/details/92085029