aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Question On Thread Safety Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Question On Thread Safety" Watch "Question On Thread Safety" New topic
Author

Question On Thread Safety

Luke
Greenhorn

Joined: Sep 14, 2005
Posts: 10
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

Joined: Sep 29, 2002
Posts: 47
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

Joined: Sep 14, 2005
Posts: 10
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question On Thread Safety