-- I am trying to make the ServletContext synchronize because when 2 or more clients, are trying to modify the same servletcontext attributes, then that will be a problem. Because Servlet A tries to set context attribute as context.setAttribute("A","test1"); and Servlet B tries to set context attribute as context.setAttribute("A","B related code"); It could happen because Servlet B doesn't know that Servlet A also has the same attribute. That will be a problem as now servlet A will get the output as "B related Code" instead of "test1" if both acces the same code at a time, and Servlet B changes before servlet A recieves the response
--If clientA write synchronize(getServletContext()) and in that he sets 2 attributes context.set("A","test1") and context.set("B", "test2"), clientA first gets the lock on the ServletContext object.
--But another person (clientB) from another servlet also try to access the synchronize(getServletContext()) method and try to replace the values of the attributes "A" and "B" when clientA's lock is still there.
Will clientB can access it...? I think no, because clientA has already lock.
-- Now my question is, will clientB will able to run his Servlet or any other client can run their servlets, on the same context , as clientA has already a lock on contextobject. And for the servlet to run, the servlet should be on running on that context itself and since the lock has already been obtained for that context, how can other client requests be servered for anyting ( I meant not only for the attributes but any other code in it), until clientA releases the lock ?
NOTE: I think that getServletContext() will return the same context reference always instead of creating with the "new" operator each time. i.e, singleton object.
It looks like you are trying to use ServletContext for user specific data - this is completely contrary to the whole idea of the javax.servlet.ServletContext interface.
Is there any reason you can't use the normal approach of keeping user specific data in a session or a database?
Joined: Jul 29, 2011
I got through this scenario when I was making some R & D. So I am looking for the clarification, on how to proceed if we are in this type of scenario. Ofcourse, we can go with request, session or any properties file or database. But I am looking into this direction.
Once a thread gets a lock on an object then other threads cannt use the synchronized(only) members of that object .So here in this scenario ofcourse yes clientB cannt use setAttribute() until clientA releases the lock on servletcontext but clientB can use the servlet context's other non-sync members.