If I have a Central Servlet called "MainServlet.java", in its doGet method I have
public void doGet(...,...) { handleFile() // open a file and write to the file }
public void handleFile() { // open file // write something on it // close the file }
Now my concern is --- Since this "MainServlet" can be called simultaneously by everybody using the web, do I need to do anything to make the File open/write/close be safe ? Theoretically it seems to me that since I am doing things in the doGet() method everything should be thread safe, and servlet API handles the multithread issue for me. SO I don't see any problem with it. Could you share what you think ?
Nope, J2EE can provide transactional support but a servlet read/writing a file not in the form of a transaction will have threading issues. Its one of the reasons J2EE tends to steer people away from file read/write patterns.
Since file reading/writing a file is VERY costly especially in a multi-threaded environment where you may have unncessary reads, I suggest a singleton pattern of some kind to ensure the file isn't being read dozens of times a minute and never written to. For performance reasons, you could also declare a int semaphore on the file which I did once when implementing a caching mechanism in J2EE. Finally, you could store the file in a database which then could be supported by a transaction.
You have over 100 posts, please do not post the same question in multiple forums, it creates duplicate conversations and wastes the time of the people trying to help you.