aspose file tools*
The moose likes Servlets and the fly likes thread safe issue and file open/write Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Reply locked New topic
Author

thread safe issue and file open/write

Artemesia Lakener
Ranch Hand

Joined: Jun 21, 2005
Posts: 162
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 ?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61437
    
  67

SO I don't see any problem with it.


The servlet API does no such thing for you. If you try to write to the same file from multiple threads, you will run into issues.

You will need to synchronize access to the file.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Scott Selikoff
author
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3710
    
    5

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.


My Blog: Down Home Country Coding with Scott Selikoff
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

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.

http://www.coderanch.com/t/378190/java/java/Does-help-prevent-writing-common
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread safe issue and file open/write