How to prevent static methods from being accessed simultaneously with multiple Servlet threads

here is the code i used for
Deletion and renaming of a large number of files within a directory.

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(); } 
+4
source share
2 answers

Option 1:

change public static void updateRootFile to public static synchronized void updateRootFile

Option 2:

Add Member to Servlet Class

 private final static Object lock = new Object(); 

then wrap the code inside the updateRootFile method in

 synchronized(lock) { .... } 

The difference is that Option 1 blocks the entire servlet class (all its synchronized methods), while Option 2 allows you to call other servlet methods from threads other than updateRootFile()

I believe one of the most definitive guides here . Chapters 07 - 11 relate to multi-threaded code.

+7
source

You can use the synchronized method for this. you can read about it here

 public synchronized static void updateRootFile 
+3
source

Source: https://habr.com/ru/post/1387525/


All Articles