Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use VAVR collections to be thread safe?

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??
    }
}    
like image 880
Rafael Paulino Avatar asked Dec 23 '22 09:12

Rafael Paulino


1 Answers

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.

like image 192
Nándor Előd Fekete Avatar answered Jan 14 '23 18:01

Nándor Előd Fekete