How to make context attribute thread safe?

Suppose there a large web application. Many servlets are there. One of the servlet contains the below code.
doGet{
getServletContext.setAttribute(“att1”,”50”);
getServletContext.setAttribute(“att2”,”100”);
getServletContext.getAttribute(“att1”);
getServletContext.setAttribute(“att2”);}
Here there is no guarantee that it will give 50 for att1 and 100 for att2, what is the reason behind it?
Many servlet are running simultaneously and context scope is not thread safe. At the same time other servlets may change the value of att1 and att2.(an other servlet’s setAttribute() method executed during that)
So how to make the context attribute thread safe?
Can we make this by synchronizing doGet() method? If we synchronize the doGet() method of the servlet that means only one thread can in the servlet can run at time, but it can not stop the other servlets and jsps from accessing the attribute. So it can not be a solution.
So here you need to lock the context. So only one thread acquire the lock and execute, during that time no other threads are allowed to access the context.
So we can write the previous code like this:
doGet{
synchronized(getServletContext){
getServletContext.setAttribute(“att1”,”50”);
getServletContext.setAttribute(“att2”,”100”);
getServletContext.getAttribute(“att1”);
getServletContext.setAttribute(“att2”);}}
Now there is guarantee that you will get att1=50 and att2=100
Since we have context lock it is sure that once we get inside the block no other threads are allowed to enter into the block.

No comments:

Post a Comment