Closed
Description
Java 8 introduced computeIfAbsent
on ConcurrentHashMap
:
If the specified key is not already associated with a value,
attempts to compute its value using the given mapping function
and enters it into this map unless {@code null}. The entire
method invocation is performed atomically, so the function is
applied at most once per key.
Since SessionRegistryImpl
uses ConcurrentHashMap
and since it uses it as <String, List<?>>
, it seems like an ideal circumstance to make the update to principals
atomic.
Instead of:
Set<String> sessionsUsedByPrincipal = principals.get(principal);
if (sessionsUsedByPrincipal == null) {
sessionsUsedByPrincipal = new CopyOnWriteArraySet<>();
Set<String> prevSessionsUsedByPrincipal = principals.putIfAbsent(principal,
sessionsUsedByPrincipal);
if (prevSessionsUsedByPrincipal != null) {
sessionsUsedByPrincipal = prevSessionsUsedByPrincipal;
}
}
sessionsUsedByPrincipal.add(sessionId);
It could do:
principals.computeIfAbsent(principal, key -> new CopyOnWriteArraySet<>())
.add(sessionId);