Search code examples
javaweb-applicationsfile-iojsp-tagsconcurrentmodification

synchronized block in JSP tag class


I am trying to find answer for the following ,for the past couple of days ,but couldnt find comprehensive answer

Problem Statement

I have a custom JSP tag class which handles a web form submission ,captures data and write it to same file in the filesystem. As all web applications,this can be triggeredsimultaneosly ,and i fear that multiple threads would be in action handling each of the submission (we all know thats how Servlet works.)

CODE

                        synchronized (this){
                        final String reportFileName = "testReport.csv";
                        File reportDir = new File( rootCsDirectory, "reports" );
                        if(!reportDir.isDirectory())reportDir.mkdir();                          
                        File reportFile = new File (reportDir, reportFileName);
                        logReport(reportFile,reportContent.toString());
                        }

ISSUE: - A File object can be opened by one thread for writing and at same time another thread might try to access and fail and throw an exception So i thought of synchronizing (on the object ) should solve the issue , but read some where that jsp engine would have pool of jsp tag objects, so i am afraid that synchronized (this) wont work and it should be changed to synchronized (this.getClass()) FYI: The code above is placed in JSP Custom Tag Class.

EDIT:

Question 1: should the block of code be synchronized by synchronized (this) OR synchronized (this.getClass())

Question 2: How the same scenario would be handled if the web application is deployed in the clustered environment ?


Solution

  • I would synchronise at a finer level, and choose an object that is more tightly tied to the file creation.

    e.g. abstract out the above into a FileManager class, and let a single instance of that synchronise on a lock object (held internally to the FileManager - it could lock on itself, perhaps).

    That way you're controlling the synchronisation at a finer level, and you have more control of the objects that you're locking on. They're not controlled by your servlet/web container.