Thread Safety of ServletContext objects

As Suggested by @Artem Moskalev, You can use ConcurrentHashMap and use putIfAbsent method to store the object/values instead of simple put method.

I wanted to add this comment below @Artem Moskalev's answer but i don't have enough reputation for this.


The best way in a multithreaded environment is to use java.util.concurrent.ConcurrentHashMap. It is designed specifically in a way that allows you to read and modify it without any ConcurrentModificationException. Nevertheless, in case of iteration you should synchronize on its instance, in order to always get the predicatble results.

Synchronizing on the context gives you a lot of overhead, if you retrieve anything else from there in a multithreaded manner. So ConcurrentHashMap is a better solution.

You can read about it here:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).


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)