9

I am storing a HashMap object in my ServletContext. But Multiple Request thread are reading and Modifying this HashMap.

As i belive the ServletContext objects are shared between request threads do i need to Synchronize the access to this HashMap ? Or is there any other better ways to achive the same ?

Linus
  • 880
  • 13
  • 25

5 Answers5

19

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)

isnot2bad
  • 24,105
  • 2
  • 29
  • 50
  • I just got confused a little with the terms. On the one hand, you say setting attributes in _ServletContext_ is thread-safe, on the other - the proper synchronization must be used. I thought, synchronization is used exactly for the purpose to protect context attributes that are NOT thread-safe. Correct me if I'm wrong. – escudero380 Sep 01 '19 at 08:44
  • 1
    @escudero380 what I mean is that every implementation of the _Java Servlet Specification_ **must** use proper synchronization within `setAttribute`, otherwise it cannot fullfil the cited requirement from chapter 4.5. – isnot2bad Sep 05 '19 at 12:01
  • @escudero380 I've slightly changed the answer and added another clarification section to address this issue. – isnot2bad Sep 05 '19 at 12:53
  • Thank you for clarification. Anyway, from what I understand, context-scoped attributes mostly exist for the purpose of storing read-only values that get set when the application is being loaded, but not necessarily a good place to share request time generated values... and in a distributed environment, such attributes seem to be not accessible for the entire cluster, so with perspective of scaling up the project, some external resource like database should be used instead as location to share global information on application-level – escudero380 Sep 05 '19 at 15:13
  • @escudero380 I totally agree. – isnot2bad Sep 07 '19 at 12:24
4

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.

João Mendes
  • 1,719
  • 15
  • 32
Swaraj
  • 345
  • 3
  • 17
1

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).

Artem Moskalev
  • 5,748
  • 11
  • 36
  • 55
0

Yeah, make sure that when you modifying the HashMap; it is synchronized or thread safe.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
-1

You need to synchronize your ServletContext object. for eg:-

synchronized(ctx){
 //your code here
}
Madhura
  • 551
  • 5
  • 18
  • As a general rule, you should not use the intrinsic (monitor) lock of an object that you do not control. – kbolino Feb 19 '15 at 02:21