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??
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With