How to correctly use VAVR collections to be thread safe?

大城市里の小女人 提交于 2019-12-07 12:24:24

问题


VAVR collections are "immutable".

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?

For example:

@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??
    }
}    

回答1:


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));
    }

}

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.




回答2:


For this use case you could also consider using a concurrent map:

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

    private static ConcurrentMap<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void open(Session session) {
        sessions = sessions.putIfAbsent(session.getId(), session);
    }

    @OnClose
    public void close(Session session) {
        sessions = sessions.remove(session.getId());
    }

}


来源:https://stackoverflow.com/questions/48908219/how-to-correctly-use-vavr-collections-to-be-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!