• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question On Thread Safety

 
Luke
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following servlet code:

public class MyServlet extends HttpServlet
{
final static int i=0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
private HttpSession session=req.getSession();
private ServletContext ctx=getServletContext();
synchronized(ctx)
{
Object obj=ctx.getAttribute(); // code to alter obj
}
}
}

Which of the following variables in the above code are thread safe?

Choices:

A. i
B. session
C. ctx
D. req
E. obj
F. res
Correct choices:

A , C , D , and F

Now my question is why is obj not thread safe?
isn't obj a local variable?

The answer given is...

obj is not thread safe because even though the ServletContext object is synchronized, its attributes are not. They need to be synchronized separately.

can anyone explain me what they are trying to say?

Thanks
 
Gouri Bargi
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My answer would be A, D and F. I think answer C is also wrong - the variable ctx here is not thread safe. There will be one ServletContext for one web application. That means, if there are more than one servlets in the application, they all share the same ServletContext object. Synchronizing access to SErvletContext in one servlet will not guarantee that the SErvletContext object is thread safe.

I am also not able to understand the explanation

obj is not thread safe because even though the ServletContext object is synchronized, its attributes are not. They need to be synchronized separately.


I think obj is an attribute set to the ServletContext, and can be accessed from all the servlets in the web application, hence it is also not thread safe.
 
Luke
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Gouri. I am able to understand what you are trying to say. It's a very tricky question with a lot of assumptions.

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic