Publishing attributes via ServletContext#setAttribute
is thread-safe! This can be derived from the Java Servlet Specification, chapter 4.5: (...) Any attribute bound
into a context is available to any other servlet that is part of the same Web
application.(...).
(Reason: Making objects available to other servlets means also to make them available to other threads. This is only possible, if proper synchronization is used, so synchronization is mandatory for all servlet containers that implement ServletContext#setAttribute
).
So the same is also true for reading published attributes via ServletContext#getAttribute
.
But of course if an object like a HashMap
is shared between different threads, the developer must ensure that this shared object itself is accessed in a proper, thread-safe way! Using a ConcurrentHashMap
as already stated in other answers of your question, is a possible solution, but does not solve the race condition when the attribute is initialized, as the null
check will not be atomic:
ConcurrentMap<String, Object> shared = (...)servletContext.getAttribute("sharedData");
if (shared == null) {
shared = new ConcurrentHashMap<>();
servletContext.setAttribute("sharedData", shared);
}
Therefore, a ServletContextListener
can be used to initialize the context when the web application starts!
Edit: To avoid confusions
We can deduce from the Java Servlet Specification, that sharing attributes between servlets via ServletContext#setAttribute
and ServletContext#getAttribute
is indeed thread-safe.
But however it is implemented internally, set/getAttribute
can only guarantee proper publishing, it cannot guarantee proper synchronization if the shared attribute is a modifiable object that is modifed after sharing. This is technically impossible!
Example:
// servlet 1:
Person p = new Person("Keith", "Richards");
context.setAttribute('key', p); // share p
p.setName("Ron", "Wood"); // modification AFTER sharing
// servlet 2 (some time LATER):
Person p = context.getAttribute();
// now, p is guaranteed to be non-null,
// but if class Person is not thread-safe by itself, it may be any of
// - "Keith Richards"
// - "Keith Wood"
// - "Ron Richards"
// - "Ron Wood"
// (depending on the implementation of setName, it may be even worse!)
As a consequence, every servlet context attribute value must be
- immutable (via final fields) or effectively immutable, OR
- mutable, but is never mutated after sharing, OR
- implemented in a thread-safe manner (e.g. synchronized)
(This is true for all kinds of objects shared between threads in Java, not only concerning servlet context attributes)