File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

thread safe issue and file open/write

Artemesia Lakener
Ranch Hand

Joined: Jun 21, 2005
Posts: 162
If I have a Central Servlet called "", 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

Joined: Jan 10, 2002
Posts: 63866

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] [About Bear] [Books by Bear]
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3753

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.

[OCA 8 Book] [Blog]
David O'Meara

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.
I agree. Here's the link:
subject: thread safe issue and file open/write
It's not a secret anymore!