如何正确使用 VAVR 集合来保证线程安全? [英] How to correctly use VAVR collections to be thread safe?

查看:22
本文介绍了如何正确使用 VAVR 集合来保证线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VAVR 集合是不可变的".

VAVR collections are "immutable".

那么,如果我有静态变量,例如,保存所有的 WebSocket 会话,我将如何使用 VAVR 以便集合是线程安全的?

So, if I have static variable, for example, holding all the WebSocket sessions, how would I use VAVR so that the collection is thread safe?

例如:

@ServerEndpoint("/actions")
public class DeviceWebSocketServer {

    private static Set<Session> sessions = //???; // how should I initialize this?

    @OnOpen
    public void open(Session session) {
        sessions = sessions.add(session); // is this OK???
    }

    @OnClose
    public void close(Session session) {
        sessions = sessions.remove(session); // is this OK??
    }
}    

推荐答案

您可以将不可变的 vavr 集合包装在原子可更新的 AtomicReference,并使用其更新方法之一以原子方式更新对不可变集合的引用.

You can wrap the immutable vavr collection in an atomically updatable AtomicReference, and use one of its update methods to atomically update the reference to the immutable collection.

@ServerEndpoint("/actions")
public class DeviceWebSocketServer {

    private static AtomicReference<Set<Session>> sessionsRef = 
            new AtomicReference<>(HashSet.empty());

    @OnOpen
    public void open(Session session) {
        sessionsRef.updateAndGet(sessions -> sessions.add(session));
    }

    @OnClose
    public void close(Session session) {
        sessionsRef.updateAndGet(sessions -> sessions.remove(session));
    }

}

请务必阅读 AtomicReference 如果您打算在其他场景中使用它们,因为需要遵守更新函数的一些要求才能获得正确的行为.

Make sure you read the javadoc of AtomicReference if you are going to use them in other scenarios, as there are some requirements on the update functions that need to be respected to get correct behavior.

这篇关于如何正确使用 VAVR 集合来保证线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆