Sun River
Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ...
posts - 78,comments - 0,trackbacks - 0
Question 1:

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

Explanation:

The static variable i is thread safe because it is final (cannot be modified), or else it would not have been safe. Request and response objects are scoped only for the lifetime of the request, so they are also thread safe. Session and ServletContext objects can be accessed from multiple threads while processing multiple requests, so they are not thread safe. However, in this case, the ServletContext object is synchronized, so it can be accessed only by one thread at a time. obj is not thread safe because even though the ServletContext object is synchronized, its attributes are not. They need to be synchronized separately. Hence choices B and E are incorrect and choices A, C, D and F are correct.

Question 2:

Which of the following statements are true?

Choices:

  • A. Multiple instances may be created on a servlet implementing SingleThreadModel
  • B. No more than one instance is created for a servlet implementing SingleThreadModel
  • C. Even static variables in a SingleThreadModel servlet are thread safe
  • D. If no threading model is implemented, by default a servlet is executed in a multi-threaded model

Correct choices:

  • A and D

Explanation:

When SingleThreadModel is implemented, the servlet container ensures that only one thread is executing the servlet's method at a time. So what will happen for multiple requests? In that case, the container may instantiate multiple instances of the servlet to handle multiple requests, so option A is correct and B is incorrect.

If the SingleThreadModel interface is not implemented, a servlet uses the multi-threaded model (that is, multiple threads can access the methods of the servlet). Static variables can be accessed through multiple instances of the same class, so they are not always thread safe. Hence choices B and C are incorrect and choices A and D are correct.

posted on 2006-10-08 04:29 Sun River 阅读(247) 评论(0)  编辑  收藏 所属分类: Servlet & Jsp