java - 我真的应该关心 servlet Action 类中的线程安全问题吗

标签 java multithreading servlets thread-safety

servlet 类处理传入的请求对象,获取数据并存储到 StringBuilder/StringBuffer 中,并将数据传递给另一个类以写入文件。

ActionClass
    public void doPost(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException {
        String fileName = request.getparameter("fileName");
        String body = request.getParameter("innerHTML");
        String head = request.getParameter("headContents");

        StringBuilder sbr = new StringBuilder();
        sbr.append(body);  sbr.append(head);
                        OR
        StringBuffer sbf = new StringBuffer();
         sbf.append(body);  sbf.append(head);

   FileWrite fw = new FileWrite(fileName, sbf/sbr); /* write the data into file*/
          }

文件写入

    class FileWrite{
       public FileWrite(String fileName, StringBuilder sbf){
        boolean isExist = checkFileName(fileName);  /* return true or false */
         if(isExist){
           String name =  reName(fileName);  /* rename & return new name */
                 /* write the file in new file */
          }else{  /* write in same file name */  }
      }

   public String reName(String oldName){
             /* rename oldName as newName & checks via isExist(newName) */
            } 

   public boolean isExist(String filename) {
         // checks the file in directory, if found already
       return true;
           else return false;
         }
    }

正如您在上面的示例中看到的,操作类将数据传递给FileWrite 类,后者将数据写入新文件。有数百个客户端可能同时发送请求以将数据存储在新文件中。
所以我的问题是,在servlet类中我应该使用什么来存储数据。String还是stringBuffer还是StringBuilder?是线程安全的问题吗?

最佳答案

是的,您应该关心线程安全问题,但线程安全问题并不在于您选择 String 或 stringBuffer 或 StringBuilder。

您需要(可能)注意线程安全的地方是,如果您的 FileWriter 类收到对同一文件名的两个请求。

此外,我要指出的是,从安全角度来看,直接从 get 参数获取原始文件位置是非常危险的 - 因为用户可以覆盖其他用户文件,或者(可能,取决于权限)甚至操作系统文件。

关于java - 我真的应该关心 servlet Action 类中的线程安全问题吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8177391/

相关文章:

java - 登录多线程应用程序

java - JSP 登录注销使用 bean 的简单 Web 应用程序 - 当数据库中存在数据时返回 false

java - 资源本地到 JTA

java - Elasticsearch 不启动

c++ - 为什么竞赛条件的输出不是随机的?

java - Servlet JSP web.xml

java - Spring Maven 应用程序中的单个无状态 Servlet

java - RunWith(PowerMockRunner.class) 不适用于包注释

javascript - 如何将多个表格的内容下载到一个csv文件

java - 在Java中,对字符串的只读访问是否需要同步?