如何防止多个Servlet线程一次访问静态方法

时间:2011-12-22 07:50:17

标签: java multithreading servlets synchronization

这是我用于的代码 删除并重命名目录中的大量文件。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    RootSipResourceApp.updateRootFile(strDirectorypath, strappID, appNames);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);
}

public static void updateRootFile(String directorypath, String appID, String[] appName) 
  throws IOException {
    try {
        FileInputStream fin = null;
        File[] listOfFiles=fileLists(directorypath);
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                rootFiles = listOfFiles[i].getName();
                if (rootFiles.endsWith(".properties") || rootFiles.endsWith(".PROPERTIES")) {
                    fin = new FileInputStream(directorypath + rootFiles);
                    properties.load(new InputStreamReader(fin, Charset.forName("UTF-8")));
                    String getAppName = properties.getProperty("root.label." + appID);
                    String propertyStr = "root.label." + appID;
                    saveFile(fin, getAppName, directorypath + rootFiles, propertyStr, appName[i]);
                }
            }
        }
    } catch (Exception e) {
        System.out.println("expn-" + e);
    }
}

public static void saveFile(FileInputStream fins, String oldAppName, String filePath, String propertyStr, String appName)
  throws IOException {
    String oldChar = propertyStr + "=" + oldAppName;
    String newChar = propertyStr + "=" + appName;
    String strLine;
    File f1 = new File(filePath);
    File f2 = new File("C:\\Equinox\\RootSipResource\\root\\root_created.properties");
    BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(f1), "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f2), "UTF-8");
    while ((strLine = br.readLine()) != null) {
        strLine = strLine.replace(oldChar, newChar);
        out.write(strLine);
        out.write("\r\n");
    }
    out.flush();
    out.close();
    br.close();
    fins.close();
}

2 个答案:

答案 0 :(得分:7)

选项1:

public static void updateRootFile更改为public static synchronized void updateRootFile

选项2:

将成员添加到servlet类

private final static Object lock = new Object();

然后将updateRootFile方法中的代码包装到

synchronized(lock) {
   ....
}

不同之处在于选项1锁定整个servlet类(所有其同步方法),而选项2允许从除updateRootFile()之外的其他线程调用其他servlet方法

我相信最权威的导游之一is here。第07章至第11章与多线程代码有关。

答案 1 :(得分:3)

您可以使用synchronized方法。你可以阅读它here

public synchronized static void updateRootFile