Having to use setAttribute()
and getAttribute(String)
in javax.servlet.ServletContext
, I cannot find any information on the intended behavoir with concurrent access. However, these operations may very well be called by different threads.
The servlet specification 3.0 states:
A servlet can bind an object attribute into the context by name. Any attribute bound into a context is available to any other servlet that is part of the same Web application.
However, there is no information on concurrency behavior of these operations. A look into the source code of Apache Tomcat reveals that it is implemented as a ConcurrentHashMap, thus making it effectively thread-safe.
My question is, should I always treat these operations as not thread-safe and have the application handle the synchronisation, or is there a piece of information that I am missing?
You can safely assume you can call getAttribute and setAttribute without synchronizing on anything, but you should make the objects you store there threadsafe (the easiest way being to store things that are immutable). The question linked in the comments is about storing a mutable object in the servletContext, in which case threads using it need to acquire its lock first (which the accepted answer explains).
There's not a spelled-out requirement. This is covered in Java Concurrency in Practice, section 4.5.1 Interpreting Vague Documentation: