Threadsafe java servlet

时间:2009-07-28 15:16:28

标签: java servlets multithreading

就线程而言,我需要知道以下代码是否存在任何问题。我一直认为,只要不使用类级别变量,线程就不是问题。

public class UploadReferralImage extends HttpServlet
{
    String CLASS_NAME = "UploadReferralImage";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
   // Not handling Get, service must be invoked via Post.
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String METHOD_NAME = "doPost";
    LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Made it to the servlet");
    String reply = upload(request);
    response.setHeader("Content-Type", "text/xml");
    response.getWriter().write(reply);
    response.getWriter().flush();
    response.getWriter().close();
}

public String upload(HttpServletRequest request)
{

    String METHOD_NAME = "upload";
    LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Inside upload");
    String replyMsg = "Unable to call ImageUpload";

    try
    {
        ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
        FileBean fBean = (FileBean) inputFromApplet.readObject();

        inputFromApplet.close();
        LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, fBean.getFileName());

        replyMsg = doImageUpload(fBean);

        } 
        catch (IOException e)
    {   
        e.printStackTrace();
            replyMsg = "Exception :" + e.toString();

    } 
        catch (ClassNotFoundException e)
    {
        e.printStackTrace();
            replyMsg = "Exception :" + e.toString();
    }

    return replyMsg;
}

private String doImageUpload(FileBean fBean)
{
       //Save the file and return the response
       SaveCaseClientAgent saveCaseClientAgent = new SaveCaseClientAgent();
       saveCaseClientAgent.save(fBean);
}

2 个答案:

答案 0 :(得分:3)

你是对的。

只要您远离使用类级别变量,Servlet将是线程安全的。

为了安全起见,不妨让您的班级String final

final String CLASS_NAME = "UploadReferralImage";

答案 1 :(得分:1)

通常,servlet容器中只有一个servlet实例,它一次重复处理多个请求。因此,由于种族条件的原因,使用实例变量将事物从一种方法传递到另一种方法是一种想法。

最好(也是最简单)的解决方法是编写自己的“处理程序”类,每个请求都会实例化一次并将所有内容传递给它。在代码中它看起来像:

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
   new MyHandler().doGet(req, resp);
}

现在在MyHandler中重用实例变量就像它获得的一样安全。