// in a context listener
public void contextInitialized(ServletContextEvent sce) {
SessionListener.context = sce.getServletContext();
HashMap<String, String> messages = new HashMap<>();
context.setAttribute("messages", messages);
}
Now I want to access the messages map from various servlets – what about synchronization ?
Namely I want to add an element to the map (whose key must be unique) – so I have to try a couple of times maybe – except if there is some method in the java ee api (?)
EDIT : interested also in synchronizing access to a session scoped map
This map is a non-thread-safe object shared by multiple threads. So every access to the map should be synchronized. You have various options:
Collections.synchronizedMap()or ConcurrentHashMap. This will never let the map in an inconsistent state, but additional synchronization could still be needed for operations that should be atomic but involve several method calls on the mapThe third solution is probably the best one. The second one might be OK if the operations on the map are very simple, and coveredby methods of the map.
Regarding the generation of unique and random strings, you could combine a UUID (for uniqueness) and a Random (or SecureRandom, depending on your requirements), for the randomness.