I created a class that implemented ServletContextAttributeListener without the default constructor and the container complained:
SEVERE: Error configuring application listener of …..
java.lang.InstantiationException: …
So I created a default constructor in addition to parameterized constructor and everything worked fine. Since the container requires a default constructs, I suspected that the container is creating a new instance of the class and not using the instance that is already created. But inserting a static object counter member data, I found this suspicion to be true.
My question is: If I want to update the member data of my object on ServletContextAttributeEvent, can I do it in a thread-safe manner? What are the side effects of container creating a new object and what are the workarounds?
Yes, the container instanciates it for you. And yes, this object being unique for the whole webapp (in a JVM), you must make sure everything is done in a thread-safe way, using synchronization. I don’t see any side-effect or workaround. That’s how it’s supposed to be.
You seem to confuse attributes and listeners. You may set and remove any attribute, of any type, to the servlet context. These attributes should not implement
ServletContextAttributeListener.You may also, on the other hand, register listeners, either via the web.xml, or by calling one of the
addListenermethods ofServletContext. Those listeners are not servlet context attributes.If you have registered one
ServletContextAttributeListenerto the servlet context, then each time you set or remove any attribute to/from the servlet context, the listener’s appropriate method will be called. The name and value of the attribute that has been set or removed will be inside the event received by the listener.So, since the container handles several requests in parallel, and since each request may set or remove attributes from the servlet context, the listener will be called multiple times in parallel, and must thus be thread-safe.